Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can make your property <a href="http://msdn.microsoft.com/en-us/library/79b3xss3" rel="nofollow">static</a>, as pointed out by many others.</p> <pre><code>public static string Name{ get{ return "David"; } } </code></pre> <p>Be aware that this means your instances of MyClass will no longer have their own Name property, since static members belong to the class, not the individual object instances of it.</p> <p><strong>Edit:</strong> In a note, you mentioned that you want to override the Name property in subclasses. At the same time, you want to be able to access it at the class level (access it without creating an instance of your class).</p> <p>For the static properties, you would simply create a new <code>Name</code> property in each class. Since they are <code>static</code>, you're always (almost always, yay reflection) going to access them using a specific class, so you'd be specifying which version of <code>Name</code> you want to get. If you want to try and hack polymorphism in there and get the name from any given subclass of MyClass, you could do so using reflection, but I wouldn't recommend doing so.</p> <p>Using the example from your comment:</p> <pre><code>public class Dad { public static string Name { get { return "George"; } } public class Son : Dad { public static string Name { get{ return "Frank"; } } public static void Test() { Console.WriteLine(Dad.Name); // prints "George" Console.WriteLine(Son.Name); // prints "Frank" Dad actuallyASon = new Son(); PropertyInfo nameProp = actuallyASon.GetType().GetProperty("Name"); Console.WriteLine(nameProp.GetValue(actuallyASon, null)); // prints "Frank" } </code></pre> <p><strike>As a side note, since you are declaring a property that has only a getter and it is returning a constant value, I recommend possibly using a <a href="http://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx" rel="nofollow">const</a> or static <a href="http://msdn.microsoft.com/en-us/library/acdd6hb7%28v=VS.71%29.aspx" rel="nofollow">readonly</a> variable instead.</p> <pre><code>public const string Name = "David"; public static readonly string Name = "David"; </code></pre> <p>Usage for both would be the same:</p> <pre><code>string name = MyClass.Name; </code></pre> <p>The main benefit (and drawback) of <code>const</code> is that all references to it are actually replaced by its value when the code is compiled. That means it will be a little faster, but if you ever change its value, you will need to recompile ALL code that references it.</strike></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload