Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Constant Custom Class

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?

like image 244
ThoughtCrhyme Avatar asked Jul 17 '26 18:07

ThoughtCrhyme


2 Answers

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:

  • readonly keyword C#
  • const keyword C#
like image 95
Mario J Vargas Avatar answered Jul 19 '26 07:07

Mario J Vargas


You can't make a reference type (besides string) const. Use the static and readonly keywords.

like image 22
Daniel A. White Avatar answered Jul 19 '26 07:07

Daniel A. White



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!