Click here to Skip to main content
15,889,721 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I wanted to declare and initialize a const of datatype Version in a class. But I am getting error CS0133 when I write code as below:
Quote:
public const Version LegacySupportedVersion = new Version("1.3.0.1");
.

How can I initialize Version type const in my class. Thanks in advance.

What I have tried:

Quote:
public const Version LegacySupportedVersion = new Version("1.3.0.1");
Posted
Updated 3-Aug-22 6:08am

public static readonly Version LegacySupportedVersion = new Version("1.3.0.1");


or

public static Version LegacySupportedVersion {get;} = new Version("1.3.0.1");
 
Share this answer
 
To add to what Gerry has - rightly - said, you can't assign a value to a const field unless it can be evaluated as a constant value at compile time. Since the new operator constructs an instance on the heap while your code is running, you cannot use that to assign a const value.

readonly will do it, since it can only be assigned a value in the declaration line or in the containing class constructor: readonly keyword - C# Reference | Microsoft Docs[^]
The other solution is to create a property with either a private setter, or no setter at all and a constant value returned in the getter - but that's messy.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900