const and static readonly - Difference.

G

Guest

Hi Pals,
I am confused between const and static readonly in C#. I want to know the
difference between then. Please give me clear explanation.
thanks in advance.
 
G

Guest

Dear Kavitha,
The difference is that the value of const is set to a compile time constant,
whereas the static readonly is set at runtime and can be modified by the
containing class (that too only in the variable declaration and in the static
constructor).

Note: Use static readonly when the value is not known at compile time.

Rgds,
John Paul. A
MCAD
 
C

Cor Ligthert

Kavitha,

Did you know that there is a special group for language questions.

microsoft.public.dotnet.languages.csharp

Not that you are not welcome here, however that is more for questions as
this.

(The Static keyword has a complete different meaning in VBNet by instance)

Cor
 
G

Guest

Can you give me an example please.

John Paul. A said:
Dear Kavitha,
The difference is that the value of const is set to a compile time constant,
whereas the static readonly is set at runtime and can be modified by the
containing class (that too only in the variable declaration and in the static
constructor).

Note: Use static readonly when the value is not known at compile time.

Rgds,
John Paul. A
MCAD
 
G

Guest

Dear Kavitha,
Note: Please post the language specific queries to this newsgroup
microsoft.public.dotnet.languages.csharp

Here's the example: The code is self explanatory.

class TestClass
{
public string MachineName;
}


class TestMachine
{
public static readonly TestClass objTestClass = new TestClass();

static void Main(string[] args)
{
objTestClass.MachineName = "PLC 134";

objTestClass = new TestClass(); // It will give an error
message
}
}

Rgds,
John Paul. A
MCAD
 
G

Guest

Yes I Do. thanks for your code.

John Paul. A said:
Dear Kavitha,
Note: Please post the language specific queries to this newsgroup
microsoft.public.dotnet.languages.csharp

Here's the example: The code is self explanatory.

class TestClass
{
public string MachineName;
}


class TestMachine
{
public static readonly TestClass objTestClass = new TestClass();

static void Main(string[] args)
{
objTestClass.MachineName = "PLC 134";

objTestClass = new TestClass(); // It will give an error
message
}
}

Rgds,
John Paul. A
MCAD

Kavitha said:
Can you give me an example please.
 

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