error in unassigned local variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jitender
    New Member
    • Jul 2011
    • 1

    error in unassigned local variable

    i am getting an error use of unassigned local variable 'j'.......in the following code .....could you help?


    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace structure
    {
      class Program
        {
            struct jeetu   // no semi colon
            {
                public string name;
                public int rollnumber;
                public int phone;
            }
    
            static void Main(string[] args)
            {
                jeetu j;
                jeetu i;
                j.name = Console.ReadLine();
                Console.WriteLine("the name of user is :" + j.name);
                try
                {
                    j.phone = int.Parse(Console.ReadLine());
                    Console.WriteLine("phone number of user is:" + j.phone);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
    
                try
                {
                    j.rollnumber = int.Parse(Console.ReadLine());
                    Console.WriteLine("rollnumber of user is:" + j.rollnumber);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                i = j;
                Console.WriteLine("another structure is :" + i.name);
                Console.WriteLine("pho :" + i.phone);
                Console.WriteLine("roll:" + i.rollnumber); 
           }
            }
        }
    Last edited by Plater; Jul 6 '11, 01:41 PM. Reason: code tags added. Modified question
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    I was a bit confused by this too... if you don't assign i to j the program runs just fine so I don't really understand why the compiler wants to enforce this. That said, it does, so we just have to deal with it.

    The easiest way to solve your problem is to initialize j with a new statement. Alternatively, you can use the default statement.

    Code:
    jeetu j = default(jeetu);
    jeetu i;
    ...
    i = j;

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      In .NET, you must instanciate structs the same way as classes I believe, with the new keyword.
      jeetu j = new jeetu();

      Comment

      Working...