RE: Newb question
From: Madhu[C#-MVP] (MadhuCMVP_at_discussions.microsoft.com)
Date: 02/18/05
- Next message: jim: "Reflecting C# attributes"
- Previous message: jez123456: "Looping"
- In reply to: Jo Segers: "Newb question"
- Next in thread: Jo Segers: "Re: Newb question"
- Reply: Jo Segers: "Re: Newb question"
- Messages sorted by: [ date ] [ thread ]
Date: Fri, 18 Feb 2005 01:25:03 -0800
Hi Jo,
Well in C# you need to initialize the variable before you use it. In the
below case, you have declared the variable but the initialization happens
only in the for loop.
As far as the compiler is concerned if the initialization code is not
covered then you are potentially using a uninitialized variable.
Just change the snipped to the following,
TestClass jo = null;
for(int i = 0; i < 5; i++)
{
jo = new TestClass();
jo.ShowAantal();
jo.ShowSen();
}
jo.ShowSen();
This should do the trick and will not give the compiler error.
HTH
Regards,
Madhu
MVP - C# | MCSD.NET
"Jo Segers" wrote:
> Hi,
>
> I am learning C# and I get a compilerer error below, but I do not
> understand why. Can somebody explain this?
>
> Thanx in advance.
>
> jo.
>
>
> using System;
>
> class TestApp
> {
> public static void Main()
> {
> // Application entry point
> Console.WriteLine("App Start");
>
> // Test 1
> TestClass jo;
>
> for(int i = 0; i < 5; i++)
> {
> jo = new TestClass();
> jo.ShowAantal();
> jo.ShowSen();
> }
>
> jo.ShowSen(); // <-- Here I get "Unable to initialise local variable
> 'jo'???
> jo.ShowName();
>
> Console.WriteLine("App End");
> Console.ReadLine();
> }
> }
>
> class TestClass
> {
> static System.Int32 InstanceCounter = 0;
>
> public TestClass()
> {
> Console.WriteLine("[TestClass] constructed.");
> InstanceCounter++;
> }
>
> public void ShowAantal()
> {
> Console.WriteLine("[TestClass] ShowAantal called...");
> Console.WriteLine("[TestClass] Number of testclass instances: {0}",
> InstanceCounter);
> }
>
> public void ShowSen()
> {
> Console.WriteLine("[TestClass] ShowSen called...");
> Console.WriteLine("[TestClass] Dit is een testregel.");
> }
>
> public void ShowName()
> {
> Console.WriteLine("[TestClass] ShowName called...");
> Console.WriteLine("[TestClass] name is {0}", this.ToString());
> }
>
> }
>
- Next message: jim: "Reflecting C# attributes"
- Previous message: jez123456: "Looping"
- In reply to: Jo Segers: "Newb question"
- Next in thread: Jo Segers: "Re: Newb question"
- Reply: Jo Segers: "Re: Newb question"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|