I'm trying to create a constant static collection of a custom class, like so:
public class MyClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
then make a class of constant, static objects of MyClass
static class MyObjects
{
public const MyClass anInstanceOfMyClass = { Property1 = "foo", Property2 = "bar" };
}
But the compiler complains that the name "Property1" and "Property2" do not exist in the current context. Also when I do this:
public const MyClass anInstanceOfMyClass = new MyClass() { Property1 = "foo", Property2 = "bar" };
The compiler complains about Property1 and Property2 being read only. How do I initialize a constant static class of these MyClass objects correctly?
Try this:
public static readonly MyClass AnInstanceOfMyClass = new MyClass() { Property1 = "foo", Property2 = "bar" };
Watch out for static class MyObjects without an access modifier. The default is internal. If your intention is to use this within the same assembly, you'll be fine, but if you intend to use this helper class outside of your assembly, you need to use the public keyword, as follows:
public static class MyObjects
{
public static readonly MyClass AnInstanceOfMyClass = new MyClass() { Property1 = "foo", Property2 = "bar" };
}
Note that I am using Pascal case for the static properties, according to Microsoft's recommendations on C# naming conventions.
In addition to the above comments, here you can find out more information on the readonly and const keywords:
You can't make a reference type (besides string) const. Use the static and readonly keywords.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With