call a public static property on an instance of a class in csharp

To call a public static property on an instance of a class in C#, you use the "ClassName.PropertyName" syntax instead of "instance.PropertyName". Here's an example code snippet:

main.cs
public class MyClass
{
    public static string MyStaticProperty { get; set; } = "Hello, world!";
}

public class Program
{
    public static void Main()
    {
        MyClass instance = new MyClass();
        string myProperty = MyClass.MyStaticProperty;
        Console.WriteLine(myProperty); // Output: Hello, world!
    }
}
328 chars
15 lines

In the above example, we define a class MyClass with a public static property MyStaticProperty. Then, in the Main method of the Program class, we create an instance of MyClass and assign it to a variable named instance. To access the static property, we use the syntax MyClass.MyStaticProperty, which retrieves the value of the property for all instances of the MyClass class. The output of this program will be "Hello, world!".

gistlibby LogSnag