Newb question

  • Thread starter Thread starter Jo Segers
  • Start date Start date
J

Jo Segers

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());
}

}
 
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
 
Madhu[C#-MVP] schreef:
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

:

Thank you very much, I already thought that this was the problem but I
didn't know I could use TestClass jo = null; to handle this.

Thanks again.
 
Back
Top