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:
Watch out for
static class MyObjectswithout an access modifier. The default isinternal. 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 thepublickeyword, as follows: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
readonlyandconstkeywords: