Virtual/Abstract fields in C#

Is it possible to have a virtual/abstract field in a C# class? If so, how is it done?


Solution 1:

A Virtual/Abstract field? No. Fields are just there to hold data. There's nothing to implement.

You can define a Virtual/Abstract Property though.

Solution 2:

You can however have virtual or abstract properties:

public abstract string ModelName { get; set; }

Solution 3:

The first sentence of the MSDN documentation answers your question:

The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.

http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx

Solution 4:

No, a field can only be assigned to not, overridden.

However, you could probably use a property and it would look almost the same

public class MyClass {
  public int MyField; //field
  public virtual int MyProperty { get; set; }  //property
}

both get used like so:

var x = new MyClass();
Debug.WriteLine("Field is {0}", x.MyField);
Debug.WriteLine("Property is {0}", x.MyProperty);

Unless the consumer is using reflection, it looks exactly the same.