This question already has answers here:
C# Inconsistent accessibility error
(2 answers)
Closed 9 years ago.
I get a warning in my program that is
'Employee.Salaried.CalculatePay()' hides inherited member 'Employee.Employee.CalculatePay()'. Use the new keyword if hiding was intended.
for this
public double CalculatePay()
{
return ((AnnualSalary * (ManagementLevel * BONUS_PERCENT)) + AnnualSalary) / 52;
}
Anyone have suggestions on how to get rid of there warning?
public double CalculatePay()
{
return annualSalary / 52;
}
public double CalculatePay(double modifiedSalary)
{
AnnualSalary = modifiedSalary;
return AnnualSalary / 52;
}
To avoid this you would have to change the code to something like
public class A
{
public virtual void TADA()
{
}
}
public class B : A
{
public override void TADA()
{
}
}
Have a look at
virtual (C# Reference)
The virtual keyword is used to modify a method, property, indexer, or
event declaration and allow for it to be overridden in a derived
class.
When a virtual method is invoked, the run-time type of the object is
checked for an overriding member. The overriding member in the most
derived class is called, which might be the original member, if no
derived class has overridden the member.
By default, methods are non-virtual. You cannot override a non-virtual
method.
override (C# Reference)
The override modifier is required to extend or modify the abstract or
virtual implementation of an inherited method, property, indexer, or
event.
seems the parent class (or the parent of it) already has a same function CalculatePay(), so if you want to overwrite it, just declare your function as override:
public override double CalculatePay()
{
return ((AnnualSalary * (ManagementLevel * BONUS_PERCENT)) + AnnualSalary) / 52;
}
You are hiding the CalculatePay() function of your base class. If this is what you are looking to do, use the new modifier to change your code to:
new public double CalculatePay()
{
return ((AnnualSalary * (ManagementLevel * BONUS_PERCENT)) + AnnualSalary) / 52;
}
http://msdn.microsoft.com/en-us/library/aa691135(v=vs.71).aspx
Related
Can I have a base class with something similar to a virtual method that declares some partial functionality, but does not return anything, in such a way that inherited classes will execute that functionality and then proceed to return something?
Simplified example:
class Parent
{
float baseFloat;
public virtual void MyMethod()
{
baseFloat = 3.14f;
}
}
class Child : Parent
{
public override float MyMethod()
{
base.Method();
return 6.28f;
}
}
Of course this will error because the overridden method has return type float vs void. The reason I want this is that I can be sure that all derived classes will want the analogous code to baseFloat = 3.14f; which modifies a class variable, but they will have their own implementations of return 6.28f;. So currently I am copy pasting the repeating code into all derived classes, but it would be nice to just implement that once in the base class.
Thanks
[...] in such a way that inherited classes will execute that functionality and then proceed to return something?
If you look at it the other way around, you could let the method in the parent class be non-virtual and return a float, and let that method return the value of a protected virtual property that every inheriting class overrides:
class Parent
{
float baseFloat;
protected virtual float MyMethodOutput => 0;
public float MyMethod()
{
baseFloat = 3.14f;
return MyMethodOutput;
}
}
class Child : Parent
{
protected override float MyMethodOutput => 6.28f;
}
var child = new Child();
Console.WriteLine(child.MyMethod());
will then print 6.28.
I have the following classes:
public class HeaderBase
{
public int HeaderSize { get { return sizeof(byte); } }
public byte[] Content { get; private set; }
public HeaderBase(byte[] bytes)
{
Content = bytes;
}
}
public class BiggerHeader : HeaderBase
{
public new int HeaderSize { get { return sizeof(byte) + sizeof(UInt32); } }
public BiggerHeader(HeaderBase header) : base(header.Content)
{ }
}
I also have a templated method to marshal and instantiate the BiggerHeader type
public static T Get<T>() where T : HeaderBase
{
HeaderBase b = new HeaderBase(new byte[]{});
T instance = (T)Activator.CreateInstance(typeof(T), b);
return instance;
}
According to MSDN:
where T : <base class name>: The type argument must be or derive from the specified base class.
However, the value of HeaderSize is 1 and not 5 as I would have expected. Why would this be the case, and how can I instantiate an object which will use the new properties from derived types?
DotNetFiddle
Related: Generics in C# - how can I create an instance of a variable type with an argument?
new members have the same name as a base member but are otherwise unrelated. It looks like you want to make use of virtual in the base and override in the derived class.
With new you essentially silenced the warning that warned you about this. new had no functional effect.
Calls on T are resolved as if T was HeaderBase. Anything else would require the runtime to perform a dynamic binding at runtime based on the name of what you called. Imagine T t; t.Xyz();. That code would not compile because no Xyz was found statically. But you are doing the same thing! At the time of compiling the method there is no Derived.HeaderSize visible because we don't know that T is going to be Derived. It could end up being something else. That's why the call is statically bound to Base.HS. The fact that B.HS and D.HS have the same name means nothing. It's a coincidence.
Well, I believe that mainly error here is a result of bad architecture.
Let's add some improvements and make all properties, that has to be changed in every other derived class - abstract. By doing so we'll make sure that we didn't forget anything, and can start using polymorphism (override behaviour).
Let's also use some features of C# 6.0
It'll also make code more readable :
public abstract class AbstractHeader
{
public abstract int HeaderSize { get; }
public virtual byte[] Content { get; set; }
protected AbstractHeader() { }
protected AbstractHeader(byte[] bytes)
{
Content = bytes;
}
}
public class BaseHeader : AbstractHeader
{
public override int HeaderSize => sizeof (byte);
}
public class BiggerHeader : AbstractHeader
{
public override int HeaderSize => sizeof (byte) + sizeof (UInt32);
public BiggerHeader(BaseHeader header) : base(header.Content)
{
}
}
This question already has answers here:
In C#, what is the difference between public, private, protected, and having no access modifier?
(19 answers)
Closed 6 years ago.
Suppose I have a base class:
public class A {
public float someValue;
<Access Modifier Here> float SomeValue {
get {
return someValue;
}
}
}
And I want to derive from it:
public class B : A {
public float SomeProperty {
get {
return SomeValue;
}
}
}
What access modifier would I use if I want to make the SomeValue property only available to the deriving class and not anywhere else?
for only derived classes.. use protected
Protected means that access is limited to the containing class or types derived from the containing class.
This question already has answers here:
What is the difference between an abstract method and a virtual method?
(28 answers)
Closed 4 years ago.
Here is some code from MSDN:
// compile with: /target:library
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
Can anyone explain the above code with respect to the differences between abstract and virtual methods?
Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.
So, abstract methods have no actual code in them, and (non-abstract) subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.
public abstract class E
{
public abstract void AbstractMethod(int i);
public virtual void VirtualMethod(int i)
{
// Default implementation which can be overridden by subclasses.
}
}
public class D : E
{
public override void AbstractMethod(int i)
{
// You HAVE to override this method
}
public override void VirtualMethod(int i)
{
// You are allowed to override this method.
}
}
First of all you should know the difference between a virtual and abstract method.
Abstract Method
Abstract Method resides in abstract class and it has no body.
Abstract Method must be overridden in non-abstract child class.
Virtual Method
Virtual Method can reside in abstract and non-abstract class.
It is not necessary to override virtual method in derived but it can be.
Virtual method must have body ....can be overridden by "override keyword".....
Abstract Method:
If an abstract method is defined in a class, then the class should
declare as an abstract class.
An abstract method should contain only method definition, should not
Contain the method body/implementation.
An abstract method must be over ride in the derived class.
Virtual Method:
Virtual methods can be over ride in the derived class but not
mandatory.
Virtual methods must have the method body/implementation along
with the definition.
Example:
public abstract class baseclass
{
public abstract decimal getarea(decimal Radius);
public virtual decimal interestpermonth(decimal amount)
{
return amount*12/100;
}
public virtual decimal totalamount(decimal Amount,decimal principleAmount)
{
return Amount + principleAmount;
}
}
public class derivedclass:baseclass
{
public override decimal getarea(decimal Radius)
{
return 2 * (22 / 7) * Radius;
}
public override decimal interestpermonth(decimal amount)
{
return amount * 14 / 100;
}
}
an abstract method must be call override in derived class other wise it will give compile-time error
and in virtual you may or may not override it's depend if it's good enough use it
Example:
abstract class twodshape
{
public abstract void area(); // no body in base class
}
class twodshape2 : twodshape
{
public virtual double area()
{
Console.WriteLine("AREA() may be or may not be override");
}
}
I checked out MSDN and a couple other sites but I'm still not sure I got an answer for this. If you have a Parent class with a virtual function Init(), can I then--in the derived class--have an override function Init(int num) or do you simply have to create a new function for each derived class you make? If I'm not mistake, the latter would cause you to have 2 Init functions in the Child class, right? Here's sort of what I mean:
public class Parent {
protected int a;
public Parent() {
a=1;
}
public virtual void Init() {
}
}
public class Child : Parent {
public Child() {
}
//is this allowed?
public override void Init(int multiplier) {
}
//or do i have to do this and have 2 Init functions?
public void Init(int multiplier) {
}
}
You're not actually overriding the method, you're simply defining a new overload.
To be able to override a method, the base method must be declared a public (or protected) virtual (or abstract) method and your derived class must use the same exact signature.
In your case, no overridable method with that signature exists in the base class so it is not allowed. It would be allowed if an overridable method existed with the signature Init(int) but there isn't, the compiler would yield an error here.
This is not possible.
What would the parameter be if it's called from the base class?
An override needs to have the same signature, otherwise there is no point in making it virtual.
//is this allowed?
public override void Init(int multiplier) {
}
This is not an override.
Since you are introducing new multiplier it would be considered new method.
However if you do this.
public override void Init(){}
It will be override.
However if you do this in derived class it will be considered overload.
public void Init(int Multiplier)
{}
The compiler will give you an error, because "there is nothing to override".
Basically, the overridden method must match the underlying signature:
http://msdn.microsoft.com/en-us/library/ms173153.aspx