Newb question

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

}
 
G

Guest

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
 
J

Jo Segers

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top