Question

I am translating a c++ file to C# and I came across this line of code.

public property str1 Headers 
{
    virtual str1 get() override { return headers; }
}

So, when I am writing this in C#, how would it be done? Is it a virtual or an overriden property? This is defined in a class which inherits from a base class that defines this property as an abstract one.

EDIT: I think it's a property in c# and I have translated as follows. But the get method is giving an error.

public str1 Headers
{
        override get  { return headers; }
        //virtual get { return headers; }
}
Was it helpful?

Solution

Since you are overriding a property inherited from a base class, just use the override modifier on your property. For Properties, the override modifier applies to both get and set accessors.

public class YourClass : SomeBaseClass
{
     public override str1 Headers
     {
         get 
         {
              return headers;
         }
     }
}

OTHER TIPS

In C#, virtual is used when you first declare a property, method, etc. with an implementation that can be overridden. abstract is similar, but when you declare it without an implementation, so that the deriving class must override it. The syntax for properties is:

public abstract class AbsClass1
{
    // non-abstract deriving class MUST override this
    public abstract str1 Headers { get; }
}

public class Class1
{
    // deriving class may override, but doesn't have to
    public virtual str1 Headers { get { return headers; } }
}

(that is, it's applied to the whole property, not the get)

override is used when you are overriding something that was previously declared as virtual. E.g. you might have

public class Class2 : AbsClass1
{
    public override str1 Headers { get { return headers; } }
}

See also sealed and new.

In C++, you need to use use 'virtual' at the top of the inheritance tree, but it doesn't do anything further down, though by convention it's used on overriding functions. There is a hazard in C++ where subtle mismatches of signature cause functions not to act as overrides when you think that they do, and there's no way of the compiler warning you about this.

In C#, these problems were avoided by requiring 'virtual' at the top, and then 'override' on all the overrides below.

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