I'm trying to override a property in my program.
Here is basically what I'm trying to do :
class A { public int test = 7; }
class B : A { public int test = 8; }
class Program
{
static void Main(string[] args)
{
A test1 = new A();
A test2 = new B();
Console.WriteLine(test1.test);
Console.WriteLine(test2.test);
}
}
This displays 7 in both case when I'd like it to display 8 in the 2nd case....
I've tried virtual and override as well as new (public new int test = 8;)
But it doesn't seem to work
And yes I know I should use private and getters. I just want to know if it's possible ?
Edit : I'm not a native C# programmer so forgive me if i mix the terms (such as field and propertys)!
I'm trying to override a property in my program.
class A { public int test = 7; }
The problem is that int test is not a property, it is a public field. Fields cannot be overriden.
Here is an example of overriding a property:
class A {
public virtual int test {
get {return 7;}
}
}
class B : A {
public override int test {
get {return 8;}
}
}
Here is a demo of this code on ideone.
test is a field, not a property. You must change it to a property and add the virtual modifier to allow it to be overriden in a subclass. You must then use the override keyword to override the value returned in class B:
class A
{
public virtual int test
{
get { return 7; }
}
}
class B : A
{
public override int test
{
get { return 8; }
}
}
Change this
A test2 = new B();
with this
B test2 = new B();
If you create test2 as A you call A methods
Related
I don't know how to define my question (probably already asked but didn't found it).
I want to create a constructor for a class B inherited from A taking a B object as parameter used to be a copy of it.
There can be something like this :
class B : A
{
public String NewField;
public B(A baseItem, String value)
{
// Create new B to be a copy of baseItem
???; // something like : this = baseItem
// Add new field
NewField = value;
}
}
Objective is to create an object B which is the exact copy of an A object with on filed more.
Use the base keyword to call the parent class constructor, giving your parent class instance as a parameter. Then create a copy constructor in your parent, and you're done.
class A
{
public A(A a)
{
// Copy your A class elements here
}
}
class B : A
{
public String NewField;
public B(A baseItem, String value)
: base(baseItem)
{
NewField = value;
}
}
You could implement a CopyProperties method, which will copy the properties values.
using System;
public class A
{
public string Filename {get; set;}
public virtual void CopyProperties(object copy)
{
((A)copy).Filename = this.Filename;
}
}
public class B : A
{
public int Number {get;set;}
public override void CopyProperties(object copy)
{
base.CopyProperties(copy);
((B)copy).Number = this.Number;
}
}
public class Program
{
public static void Main()
{
B b = new B { Filename = "readme.txt", Number = 42 };
B copy = new B();
b.CopyProperties(copy);
Console.WriteLine(copy.Filename);
Console.WriteLine(copy.Number);
}
}
I have next code
class Base
{
public virtual int Prop { get; set; }
}
class Derived : Base
{
public override int Prop { get { return 1; } }
}
//...
Derived obj = new Derived();
int some = obj.Prop; //expected
obj.Prop = 10; //oops it works
The fact that the last line should complile seems not to be so obvious at first sight. In my program I have a situation when overriding some auto-implemented property in a such way would be a solution. I understand that it's not a good approach. What kind of refactoring can I do to avoid such inheritance and to clean my code? Thanks
A derived class has to implement the same interface as its base class - having a public setter be inaccessible from a derived class would break polymorphism.
If Prop needs to be inaccessible to clients, but you need to be able to set its value from within the class itself, you could declare it as:
public virtual int Prop { get; protected set; }
There probably isn't a single answer to this question, as it depends on the model for your specific application. If some derived classes need to allow writes to this property, but others don't, you could either throw an exception on an invalid write and handle it at run time, or perhaps implement the property using a protected backing field and only a getter, and then add a derived class that provides a SetProp() method for those classes that need it.
public class Base
{
protected int prop;
public virtual int Prop { get { return prop; } }
}
public class WriteableBase : Base
{
public virtual void SetProp(int prop) { this.prop = prop; }
}
class Base
{
public virtual int Prop { get; set; }
}
class Derived : Base
{
public new int Prop { get { return 1; } private set {} }
}
The problem is that if you cast your Derived to Base, you can set the property anyway. If the Property relay on a field, it will be overwriten.
Ex.:
class Base
{
protected int fProp;
public virtual int Prop { get { return fProp; } set { fProp = value; } }
}
class Derived : Base
{
public Derived()
{
fProp = 1;
}
public new int Prop { get { return fProp; } private set {} }
}
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//...
Derived obj = new Derived();
int some = obj.Prop; //expected
Base b = (Base)obj;
b.Prop = 10; //oops it works
Console.WriteLine(obj.Prop); =>it will show 10, not 1
Console.ReadKey();
}
}
}
A "better" approach to avoid this kind of problem is to avoid the use of a base class if you want to "change" something on a derived class. Or, put only the minimal content that must be implemente by ALL derived classes and let the derived classes implement any extra code that only they want.
Ex:
class Base
{
protected int fProp;
}
class Derived : Base
{
public Derived()
{
fProp = 1;
}
public int Prop { get { return fProp; } }
}
class Derived2 : Base
{
public int Prop { get { return fProp; } set { fProp = value; } }
}
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//...
Derived obj = new Derived();
int some = obj.Prop; //expected
Base b = (Base)obj;
//obj.Prop = 10; Compilation error
Console.WriteLine(obj.Prop);
Derived2 obj2 = new Derived2();
obj2.Prop = 10;
Console.WriteLine(obj2.Prop);
Console.ReadKey();
}
}
}
Also, you could "encapsulate" your base class:
class Derived
{
protected Base fBase;
public Derived()
{
fBase = new Base;
}
//implement enything that you need to access from Base class
public int Prop { get { return 1; } }
}
But I find this last one too "expensive"... :)
I think it´s not possible to get compiler-error in this case. Imagine further you´d declare obj not as Derived but as Base = new Derived(), how should compiler know which property to infer. So all you can do is to throw an exception during runtime within the derived setter telling that setting this property isn´t allowed fir this type.
class Base
{
public virtual int Prop { get; protected set; }
}
class Derived : Base
{
public override int Prop {
get { return 1; }
protected set {throw NotSupportedException();}
}
}
When compiling, C# transforms the getter and setter to individual methods (get_Prop and set_Prop).
Your code only implements the get in the Derived class, and the setremains that of the base class.
If this is your desired behavior, I don't find it to be wrong.
If you are trying to hide the setter in the Derived class, there is no elegant way to do it, so throwing an NotSupportedException is a solution.
class Base
{
public virtual int Prop { get; set; }
}
class Derived : Base
{
public override int Prop { get { return 1; } set { throw new NotSupportedException();}}
}
First of all, take a look at my below code:
class A
{
public static int Flag()
{
return 0;// set initial value=0
}
B b= new B();
public void afunc()
{
b.bfunc();
}
}
And class B recieves and sends static variable:
class B
{
A a= new A();
int flag= a.Flag();
public void bfunc()
{
if(flag==0)
{
flag=1;//???? is this wrong???
//do some thing
}
}
}
Class A send to B a static variable with initial value=0; then class A call bfunc from class B. In bfunc() I set flag=1. I'm a new to C#. Can you share me how class A recieves back flag=1 sended by class B. I mean which syntax?
a few things are wrong here
Flag is a method on A, so you cannot change its "value"
Flag is static therefore it does not have an instance which is what I think you want
I suspect you want Flag to be a property of A
public int Flag{get;set;}
You are making new instances of A and B, which may be correct for you but be weary this means you are not referencing existing instances
You have two options
A
this.Flag = b.bFunc();
public int bFunc()
.... return 1;
B
public void bFunc()
... a.Flag = 1;
If you really want static variable then
public static int Flag = 0;
A.Flag = x
Were is no static variable here, you only have a static function int Flag(). To get value of a flag in class A, you must return this value from function bfunc() like this:
public int bfunc()
{
if(flag==0)
{
flag=1;
return flag;
}
}
I don't know if I understood you properly because there are many things wrong with your code. Flag should be a property instead of a method so you can store your value. The way you used it was just tossing out a zero.
First, your two classes. Keep in mind that usually properties should be used as accesssors to private fields, but let's do it the simplest way.
class A
{
public static int Flag = 0;
}
class B
{
public void bfunc()
{
if (A.Flag == 0)
{
A.Flag = 1;
}
}
}
Then use them as follows to change Flag's value.
B bObject = new B();
bObject.bfunc();
// A.Flag is now 1.
Note that bfunc() will change Flag's value to 1 only if it was 0 before.
I have a base class that looks as follows
public class base
{
public int x;
public void adjust()
{
t = x*5;
}
}
and a class deriving from it. Can I set x's value in the derived class's constructor and expect the adjust() function to use that value?
Yes, that should work entirely as expected, even though your code sample does not quite make sense (what is t?). Let me provide a different example
class Base
{
public int x = 3;
public int GetValue() { return x * 5; }
}
class Derived : Base
{
public Derived()
{
x = 4;
}
}
If we use Base:
var b = new Base();
Console.WriteLine(b.GetValue()); // prints 15
...and if we use Derived:
var d = new Derived();
Console.WriteLine(d.GetValue()); // prints 20
One thing to note though is that if x is used in the Base constructor, setting it in the Derived constructor will have no effect:
class Base
{
public int x = 3;
private int xAndFour;
public Base()
{
xAndFour = x + 4;
}
public int GetValue() { return xAndFour; }
}
class Derived : Base
{
public Derived()
{
x = 4;
}
}
In the above code sample, GetValue will return 7 for both Base and Derived.
Yes, it should work.
The following, slightly modified code will print 'Please, tell me the answer to life, the universe and everything!' 'Yeah, why not. Here you go: 42'
public class Derived : Base
{
public Derived()
{
x = 7;
}
}
public class Base
{
public int x;
public int t;
public void adjust()
{
t = x * 6;
}
}
class Program
{
static void Main(string[] args)
{
Base a = new Derived();
a.adjust();
Console.WriteLine(string.Format("'Please, tell me the answer to life, the universe and everything!' 'Yeah, why not. Here you go: {0}", a.t));
}
}
Without any code in the subclasses, I'd like an abstract class to have a different copy of a static variable for each subclass. In C#
abstract class ClassA
{
static string theValue;
// just to demonstrate
public string GetValue()
{
return theValue;
}
...
}
class ClassB : ClassA { }
class ClassC : ClassA { }
and (for example):
(new ClassB()).GetValue(); // returns "Banana"
(new ClassC()).GetValue(); // returns "Coconut"
My current solution is this:
abstract class ClassA
{
static Dictionary<Type, string> theValue;
public string GetValue()
{
return theValue[this.GetType()];
}
...
}
While this works fine, I'm wondering if there's a more elegant or built-in way of doing this?
This is similar to Can I have different copies of a static variable for each different type of inheriting class, but I have no control over the subclasses
There is a more elegant way. You can exploit the fact that statics in a generic base class are different for each derived class of a different type
public abstract class BaseClass<T> where T : class
{
public static int x = 6;
public int MyProperty { get => x; set => x = value; }
}
For each child class, the static int x will be unique for each unique T
Lets derive two child classes, and we use the name of the child class as the generic T in the base class.
public class ChildA: BaseClass<ChildA>
{
}
public class ChildB : BaseClass<ChildB>
{
}
Now the static MyProperty is unique for both ChildA and ChildB
var TA = new ChildA();
TA.MyProperty = 8;
var TB = new ChildB();
TB.MyProperty = 4;
While this works fine, I'm wondering if there's a more elegant or built-in way of doing this?
There isn't really a built-in way of doing this, as you're kind of violating basic OO principles here. Your base class should have no knowledge of subclasses in traditional object oriented theory.
That being said, if you must do this, your implementation is probably about as good as you're going to get, unless you can add some other info to the subclasses directly. If you need to control this, and you can't change subclasses, this will probably be your best approach.
This is a little different than what you're asking for, but perhaps accomplishes the same thing.
class Program
{
static void Main(string[] args)
{
Console.WriteLine((new B()).theValue);
Console.WriteLine((new C()).theValue);
Console.ReadKey();
}
}
public abstract class A
{
public readonly string theValue;
protected A(string s)
{
theValue = s;
}
}
public class B : A
{
public B(): base("Banana")
{
}
}
public class C : A
{
public C(): base("Coconut")
{
}
}
There's an alternative solution which might or might not be better than yours, depending on the use case:
abstract class ClassA
{
private static class InternalClass<T> {
public static string Value;
}
public string GetValue()
{
return (string)typeof(InternalClass<>)
.MakeGenericType(GetType())
.GetField("Value", BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
}
}
This approach is used in EqualityComparer<T>.Default. Of course, it's not used for this problem. You should really consider making GetValue abstract and override it in each derived class.
What about this?
class Base {
protected static SomeObjectType myVariable;
protected void doSomething()
{
Console.WriteLine( myVariable.SomeProperty );
}
}
class AAA : Base
{
static AAA()
{
myVariable = new SomeObjectType();
myVariable.SomeProperty = "A";
}
}
class BBB : Base
{
static BBB()
{
myVariable = new SomeObjectType();
myVariable.SomeProperty = "B";
}
}
It works for me.
Would be even nicer with Interface.
Simple solution: just use word "new".
public abstract class AbstractClass
{
public static int Variable;
}
public class RealizationA : AbstractClass
{
public new static int Variable;
}
public class RealizationB : AbstractClass
{
public new static int Variable;
}
And the result:
AbstractClass.Variable = 1;
RealizationA.Variable = 2;
RealizationB.Variable = 3;
Console.WriteLine(AbstractClass.Variable); //1
Console.WriteLine(RealizationA.Variable); //2
Console.WriteLine(RealizationB.Variable); //3
or you can use property:
//in abstract class
public static int Variable {get; set;}
//in child class
public static new int Variable {get; set;}
or function (but remember to add "new" to both variable and function):
//in abstract class
protected static int Variable;
public static int GetVariable() { return Variable; }
public static void SetVariable(int v) { Variable = v; }
//in child class
protected new static int Variable;
public static new int GetVariable() { return Variable; }
public static new void SetVariable(int v) { Variable = v; }
or you can use private variables (you don't need to use "new") with functions to get and set:
//in abstract class
private static int Variable;
//get and set methods
//in child class
private static int Variable;
//get and set methods