Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can we declare a variable as Abstract ?
If Yes then What is the use of defining a variable as abstract in a Abstract Class..?
Posted
Updated 10-Sep-14 21:40pm
v2

No.
You can only declare classes as abstract, and variables as references to classes (or as value types).
You can declare a variable as a reference to an abstract class, that's fine:

C#
public abstract class MyBase { ... }
public class MyDerived : MyBase { ... }
private void MyMethod()
   {
   MyBase base = new MyDerived();
   }
And base can hold a reference to any class derived from MyBase.

Similarly, within the abstract base class, you can't declare an abstract field:
C#
public abstract string myString;
Because the derived class would have to match the signature exactly - so where is the point? The field may as well be defined in the base class.
You can however declare abstract properties:
C#
public abstract class MyBase
    {
    public abstract string MyString { get; protected set; }
    }
And then the derived classes must provide the implementation.
 
Share this answer
 
No you cannot.
When you declare a variable you declare an instance of the class/struct you specified.
Abstract classes cannot be directly instantiated.

And what would be the purpose of an abstract variable?

http://en.wikipedia.org/wiki/Abstract_type[^]
 
Share this answer
 
v2
Yes, you can, although you actually define abstract PROPERTIES, not VARIABLES. I don't think declaring variables is even possible...but I admit I am NOT sure about this.

Use: forcing the inheritor of the class to implement that particular functionality.

Say you have an invoice class, order class and return class,all of them dealing with your goods (selling, receiving from your supplier and returns from buyers). And they all have some common things to do, they have headers with two people / firm details (sender, receiver), item list, total price etc...

What you want to force everyone is to have totalAmount and totalTax fields...you would declare them Abstract and anyone inheriting from your abstract class would have to implement it (even if it returned always the same (say tax = 0) for that particular implementation.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900