Question

Not really dealt with abstract methods that much but am looking at an abstract method inside an abstract class.

    protected abstract bool Validate()
    {
    }

When I create the above class I get an error that tells me I need to specify a return type as per a normal method. Is this correct or am I doing something wrong?

Was it helpful?

Solution

If you declaring the abstract method then you should not give body

protected abstract bool Validate();

If it is not abstract method declaration but you giving implementation of an abstract method then you should return bool using return statement from method method to satisfy the return type in declartion.

protected abstract bool Validate()
{
     //The method code 
     return false;
}

An abstract method declaration introduces a new virtual method but does not provide an implementation of that method. Instead, non-abstract derived classes are required to provide their own implementation by overriding that method. Because an abstract method provides no actual implementation, the method-body of an abstract method simply consists of a semicolon, MSDN.

OTHER TIPS

Abstract method should not have body. It is yielded to the derived class to implement the method.

protected abstract bool Validate();

Take a look at the documentation:

Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation. Abstract methods have the following features: An abstract method is implicitly a virtual method. Abstract method declarations are only permitted in abstract classes. Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature.

http://msdn.microsoft.com/en-us/library/sf985hc5.aspx

In C# abstract methods do not have implementation, so your code should look like:

//no { and } in there
protected abstract bool Validate();

You cannot create an instance of an abstract class, you should create another class that is derived from you abstract class, and in that new class you implement this method.

As others mentioned abstract methods dont have bodies. The reason why they do not is that classes cant have instances. That mean youll never have object of abstract class. You have to extend abstract class and implement body in concrete class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top