C# Late Binding - c#

I have a "simple" problem, and I crated an example app to illustrate. I would like the b.getName() call to return "barname", but it does not, and I'm not sure how to get this to work. I've been working in C# for years, but at the moment I feel like a newbie because this late binding problem has me stumped.
class Program
{
static void Main(string[] args)
{
bar b = new bar();
Console.WriteLine(b.getName());
Console.ReadLine();
}
}
class foo
{
string name = "fooname";
public string getName()
{
return this.name;
}
}
class bar:foo
{
string name = "barname";
}

By default your name variable is private - it sounds like you want it to be protected, so you can overwrite the value - this would work:
class foo
{
protected string name = "fooname";
public string getName()
{
return this.name;
}
}
class bar : foo
{
public bar()
{
name = "barname";
}
}

If you're not married to having a private class variable, you can accomplish this with an overridden property:
class foo
{
public virtual string Name
{
get
{
return "fooname";
}
}
}
class bar : foo
{
public override string Name
{
get
{
return "barname";
}
}
}

This isn't related to late binding. Late binding generally refers to calling a method at runtime from the name.
What your supplied code actually does is create a new variable that's in a different scope than what your base class has access to.
In order to get the desired effect, you actually need to either 1) make the base class method implementation virtual, and override the method in your child, or 2) in your base class change your variable to have a default accessibility of protected and set the value in your derived class's constructor(s).

Related

C# - adding data custom checks to the compiling process

Context: a simple base class which holds a name and a couple methods.
public abstract class BaseElement
{
public string Name { get; set; }
public abstract object GetDescription();
public abstract void DoStuff();
}
A developer could subclass BaseElement, he will have to implement GetDescription() and DoStuff(), but can completely forget to assign a value to the Name property.
A simple solution would be to change the class this way:
public abstract class BaseElement
{
public string Name { get; private set; }
public abstract object GetDescription();
public abstract void DoStuff();
private BaseElement()
{
}
public BaseElement(string name)
{
Name = name;
}
}
So, this way when you subclass you are forced to assign a name.
Still, you can always go as far as to use null or "".
Ok, then I can add a parameter check into the ctor and throw the relative exception, but...you'll discover the mistake only at run time, after you try to use the derived class.
So, the question: is it possible to add compilation-time rules to instruct the compiler to check for variables possible values, so that the problem is discovered at compile time and not at run time?
How about like this?
public string Name
{
get { return _name; }
private set
{
if (!string.IsNullOrWhiteSpace(value))
_name = value;
else
{
throw new Exception("Exception");
}
}
}

Property returns string from base class while member returns string from inherited class?

Here is the program:
public class Program
{
static void Main()
{
MyInheritedClass InheritInstance = new MyInheritedClass();
Console.WriteLine(InheritInstance.name); // the name field
}
}
public class MyClass
{
public string name= "I am the Base"; // the name field
public string Name // the Name property
{
get
{
return this.name;
}
}
}
public class MyInheritedClass : MyClass
{
new public string name= "I inherit Base";
}
This works as expected. the output is: "I inherit Base"
Now if I change Console.WriteLine(InheritInstance.name); // the name field to Console.WriteLine(InheritInstance.Name); // the name property, it magically outputs: "I am Base"
I am baffled as to WHY this happens? I called the Name property of MyInheritedClass, how did the Name property of MyClass get called? Or maybe the Name property of MyClass is called and it somehow magically accesses the name field of MyClass?
Now if I change Console.WriteLine(InheritInstance.name); // the name
field to Console.WriteLine(InheritInstance.Name); // the name
property, it magically outputs: "I am Base"
This happens because MyClass is unaware of the new operator in your derived class. As far as it knows, it only has one string field called Name, which is declared in the base class. When the property has the retrieve it via the getter, it goes to the name declared there.
As the docs say:
When used as a declaration modifier, the new keyword explicitly hides
a member that is inherited from a base class. When you hide an
inherited member, the derived version of the member replaces the base
class version
If you want to override that behavior, you can declare name as virtual:
public class MyClass
{
public string name = "I am the Base";
public virtual string Name { get { return this.name; } }
}
public class MyInheritedClass : MyClass
{
public new string name = "I inherit Base";
public override string Name { get { return this.name } };
}
Note this looks and feels redundant. You can avoid that by declaring a single virtual property:
public class MyClass
{
public virtual string Name { get { return "I am base" } }
}
public class MyInheritedClass : MyClass
{
public override string Name { get { return "I am derived" } };
}
It calls your base class property because the Name property is defined only in the base class. This is the default and simplest behavior of inheritance. You can access properties from the base class.
When you need control over a property from the Base class you can use the override or new constructs to define your desired behavior for the property in the Child class.

Overrideable property that can be accessed both by instance and by class

I have an inheritance tree with a bunch of different classes. Each of these classes has some static properties that I need acces to from time to time. Sometimes I need the property of a particular class, and sometimes I need the property of the specific class some polymorphic instance turns out to be.
This would be easy in, say, Java (I think). Just make a bunch of static fields (can these be overriden? I'm not sure). But in C#, non-static fields can ONLY be accessed via an instance (naturally), and static fields can ONLY be accessed via their corresponding class (unnaturally).
And, you can't "overload" by, er, staticity. If a class has a static and a non static Foo, doing instance.Foo fails because it is unclear to the compiler which Foo you're referring to even though it's impossible you're referring to the static one since it's disallowed.
Ok, I'll provide some code. Say I have this:
class Base
{
public static readonly string Property = "Base";
}
class Child1 : Base
{
public static readonly new string Property = "Child 1";
}
class Child2 : Base
{
public static readonly new string Property = "Child 2";
}
And then, somewhere:
public void SomeMethod(Base instance)
{
System.Console.WriteLine(instance.Property); // This doesn't work.
}
And somewhere else:
public void SomeOtherMethod()
{
System.Console.WriteLine(Child2.Property);
}
I want something like that, that actually works.
As Peter Duniho said, this can be done with reflection.
For example, these can be defined within the base class:
public const string Property = "Base";
public virtual string InstanceProperty
{
get
{
return (string)this.GetType()
.GetField("Property", BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
}
}
And then each derived class just has to redefine Property using the new keyword.
I think the best you'll do in C# is something like this:
public class BaseClass
{
public virtual string InstanceProperty
{
get { return StaticProperty; }
}
public static string StaticProperty
{
get { return "BaseClass"; }
}
}
public class Derived1Base : BaseClass
{
public override string InstanceProperty
{
get { return StaticProperty; }
}
public new static string StaticProperty
{
get { return "Derived1Base"; }
}
}
public class Derived1Derived1Base : Derived1Base
{
}
public class Derived2Base : BaseClass
{
public override string InstanceProperty
{
get { return StaticProperty; }
}
public new static string StaticProperty
{
get { return "Derived2Base"; }
}
}

"new" keyword in property declaration in c#

I've been given a .NET project to maintain. I was just browsing through the code and I noticed this on a property declaration:
public new string navUrl
{
get
{
return ...;
}
set
{
...
}
}
I was wondering what does the new modifier do to the property?
It hides the navUrl property of the base class. See new Modifier. As mentioned in that MSDN entry, you can access the "hidden" property with fully qualified names: BaseClass.navUrl. Abuse of either can result in massive confusion and possible insanity (i.e. broken code).
new is hiding the property.
It might be like this in your code:
class base1
{
public virtual string navUrl
{
get;
set;
}
}
class derived : base1
{
public new string navUrl
{
get;
set;
}
}
Here in the derived class, the navUrl property is hiding the base class property.
This is also documented here.
Code snippet from msdn.
public class BaseClass
{
public void DoWork() { }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork() { }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
DerivedClass B = new DerivedClass();
B.WorkProperty; // Calls the new property.
BaseClass A = (BaseClass)B;
A.WorkProperty; // Calls the old property.
Some times referred to as Shadowing or method hiding; The method called depends on the type of the reference at the point the call is made. This might help.
https://msdn.microsoft.com/en-us/library/435f1dw2.aspx
Look at the first example here, it gives a pretty good idea of how the new keyword can be used to mask base class variables

Define a method in base class that returns the name of itself (using reflection) - subclasses inherit this behavior

In C#, using reflection, is it possible to define method in the base class that returns its own name (in the form of a string) and have subclasses inherit this behavior in a polymorphic way?
For example:
public class Base
{
public string getClassName()
{
//using reflection, but I don't want to have to type the word "Base" here.
//in other words, DO NOT WANT get { return typeof(Base).FullName; }
return className; //which is the string "Base"
}
}
public class Subclass : Base
{
//inherits getClassName(), do not want to override
}
Subclass subclass = new Subclass();
string className = subclass.getClassName(); //className should be assigned "Subclass"
public class Base
{
public string getClassName()
{
return this.GetType().Name;
}
}
actually, you don't need to create a method getClassName() just to get the type-name. You can call GetType() on any .Net object and you'll get the meta information of the Type.
You can also do it like this,
public class Base
{
}
public class Subclass : Base
{
}
//In your client-code
Subclass subclass = new Subclass();
string className = subclass.GetType().Name;
EDIT
Moreover, should you really need to define getClassName() in any case, I'd strongly suggest to make it a property [as per .net framework design guide-lines] since the behavior of getClassName() is not dynamic and it will always return the same value every-time you call it.
public class Base
{
public string ClassName
{
get
{
return this.GetType().Name;
}
}
}
EDIT2
Optimized version After reading comment from Chris.
public class Base
{
private string className;
public string ClassName
{
get
{
if(string.IsNullOrEmpty(className))
className = this.GetType().Name;
return className;
}
}
}

Categories