I try to get access to a function in a class that inherited from another (abstract) class. But I only have an access to property from upper class, and do not have access to the function from the class I instantieted.
public abstract class A
{
public abstract string getString { get; }
}
public class B: A
{
public override string getString
{
get => "String";
}
public string getOtherString()
{
return "oterString";
}
}
class C
{
private A localClass;
C()
{
localClass = new B();
string test1 = localClass.getString; // Works well
string test2 = localClass.getOtherString(); // Does not work
}
}
What I do wrong?
If you have an instance of A(base class) you cannot access members from B(child). You either have to declare private B localClass or cast it to B:
string test2 = ((B)localClass).getOtherString();
This fails at runtime if localClass is not of type B.
Related
Is there a way, and not using reflection, of elegant get only child propeties of an object?
For example:
class A
{
public string PropA;
}
class B : A
{
public string PropB;
}
class C
{
var classB_instance = new B();
/* Only class B properties without parent so B.PropB; but no B.PropA;
}
I know it would be possible with reflection, but if this can be avoided?
You could create a specific interface for your inherited class like say
interface ISpecificB {
string PropB;
}
and then Create your class like
public class A {
public string PropA;
}
public class B: A, ISpecificB {
public string PropB;
}
and only make the variable as specific as ISpecificB when creating it or returning it from a function
ISpecificB classB = new B();
classB.PropA // shouldn't be available
However, classB could still be casted as B or A which would give access to the propA and it might increase complexity in your solution
Whether you can do this way ?
class A
{
private string PropA;
}
class B : A
{
public string PropB;
}
class C
{
var classB_instance = new B();
}
You could mark PropA as private, look at https://msdn.microsoft.com/en-us/library/ms173121.aspx:
private
The type or member can be accessed only by code in the same class or struct.
just a short note: most of the time, I use reflection to do exactly the opposite: access things I am not allowed, for example, because they are private... ;-) reflection is not a "tool" to hide something, AFAIK. it opens every door which is usually locked ;-)
You can use the protected accessibility modifier:
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
public class A
{
protected string PropA { get; set; }
}
public class B : A
{
public string PropB { get; set; }
}
public class C
{
var classB_instance = new B();
//You can't access classB_instance.PropA
}
Declare variable PropA of Class A as private variable(as show in below code):
class A
{
private string PropA;
}
I don't know if this is possible, but I am trying to get the Base Class instance from a Derived Class. In C#, I can use the base keyword to access properties and methods of the Base Class (of course), but I want to use base itself. Attempting to do so results in a "Use of keyword 'base' is not valid in this context" error.
Example Code
public class SuperParent
{
public int SPID;
public SuperParent()
{
}
}
public class SubChild : SuperParent
{
public SubChild(int pSPID)
{
base.SPID = pSPID;
}
public int BaseSPID
{
get
{
SuperParent sp = base;
return sp.SPID;
}
}
}
If you're working with an instance of the derived class, there is no base instance.
An example:
class A
{
public void Foo() { ... }
}
class B : A
{
public void Bar() { ... }
}
What is not possible within B:
public void Bar()
{
// Use of keyword base not valid in this context
var baseOfThis = base;
}
You can do something like this:
public void Bar()
{
base.Foo();
}
And you can add another method like
public A GetBase()
{
return (A)this;
}
And then you can
public void Bar()
{
var baseOfThis = GetBase();
// equal to:
baseOfThis = (A)this;
}
So this GetBase() method is probably what you want.
The punchline is: If you have an instance of B, it inherits all properties and the non-overriden behaviour of A, but it does not consist of an instance of B which holds an (hidden but automatic) reference to an instance of A. You can cast your B instance to A, but it remains to be an instance of B.
Well you not provide code for your question, but i supsect you want something like
class Base
{
public virtual void Foo()
{
Console.WriteLine("base");
}
}
class Derived : Base
{
public override void Foo()
{
Console.WriteLine("derived");
}
//// bad
//public Base MyBase
//{
// get
// {
// return base; // Use of keyword 'base' is not valid in this context
// }
//}
// work but...
public Base MyBase
{
get
{
return (Base)this;
}
}
}
But keep in mind that MyBase is really of type Derived
new Derived().MyBase.Foo(); // output "derived"
the problem hasn't been explained as clearly as it could. however, typically, you may be better to use an abstract base class and methods and then override the required methods. you can then use the base.method as required in this case (otherwise you'll have just spun up an instance of the derived class).
public abstract class foo {
public virtual void bar(){..}
}
public class footwo : foo {
public override void bar(){
// do somethng else OR:
return base.bar();
}
}
}
The derived instance IS the base instance. It's just one object instance in memory.
example:
public class A : B
{
}
var thing = new A();
thing is an instance of an A, and is also an instance of a B.
You could for example, write this line:
B thing2 = thing;
Point 1: if you want to create the base class instance within child class than it does not worth. You already have public things accessible in child.
Point 2: If you have initialized child class and now want to get base class "instance" then how can you get that if it's not initialized(Because now the base class instance is not present in the physical memory, and there is just child class instance there)?
I interpreted what they were asking a bit differently than the other answers here so I figured I would offer my $0.02.
// Create a "Parent" class that has some attributes.
public class Parent
{
public string attribute_one { get; set; }
public string attribute_two { get; set; }
public string attribute_three { get; set; }
}
// Define a class called "Child" that inherits the
// attributes of the "Parent" class.
public class Child : Parent
{
public string attribute_four { get; set; }
public string attribute_five { get; set; }
public string attribute_six { get; set; }
}
// Create a new instance of the "Child" class with
// all attributes of the base and derived classes.
Child child = new Child {
attribute_one = "interesting";
attribute_two = "strings";
attribute_three = "to";
attribute_four = "put";
attribute_five = "all";
attribute_six = "together";
};
// Create an instance of the base class that we will
// populate with the derived class attributes.
Parent parent = new Parent();
// Using reflection we are able to get the attributes
// of the base class from the existing derived class.
foreach(PropertyInfo property in child.GetType().BaseType.GetProperties())
{
// Set the values in the base class using the ones
// that were set in the derived class above.
property.SetValue(parent, property.GetValue(child));
}
The result is a new object populated with the base class properties of the child class.
class Parent
{
private Parent _parent;
public Parent()
{
_parent = this;
}
protected Parent GetParent()
{
return _parent;
}
}
class Child : Parent
{
private Parent _parent;
public Child()
{
_parent = base.GetParent();
}
}
I have an interface for a base class, and every class that inherits from the base class should have an identifying field which tells the application what kind of object it is.
I wanted to use this property in two different ways:
Without creating an instance of the object
if (someValue == TestA.Id)
return new TestA();
elseif (someValue == TestB.Id)
return new TestB();
And as a property of the interface
void DoSomething(ITest testObject)
{
SomeValue = testObject.Id;
}
Is there an easy way to define the Id field in the interface, but still have it available to use without creating an instance of the class?
Right now I am using the following code. I could add a read-only Id property to the interface which returns the const string, however I was hoping there was a simpler way that I'm just not aware of.
public interface ITest
{
}
public class TestA : ITest
{
public const string Id = "A";
}
In short - no.
In order to be able to do this, you'd need to be able to specify this as a instance property on the interface (and implement it in the instance), and as a static property on the type.
The compiler won't let you do this.
You can put it in the interface, and also have it as a static property. Something like:
interface IInterface { Id { get; } }
class Class : IInterface
{
public static Id { get { return 1; } }
public Id { get { return Class.Id; } }
}
I've faced a similar problem, Rachel, and I've always (unfortunately) resorted to having that factory code rely on reflection to get a "TypeID" public static property on each concrete type... thus making an additional aspect of the contractual interface, but not having it in the C# interface code.
You could do it this way.
public interface ITest
{
SomeValue Id{ get;}
}
public class TestA : ITest
{
public SomeValue Id
{
get {return TestA.StaicId; }
}
public static SomeValue StaticId
{
get {return "This is TestA";}
}
}
if (someValue == TestA.StaticId)
return new TestA();
How about using attributes? Here's a small example of what can be done:
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class IdAttribute : Attribute
{
public IdAttribute(string id)
{
this.Id = id;
}
public string Id { get; set; }
}
public interface IMyInterface
{
}
public abstract class BaseClass : IMyInterface
{
public static string GetId<T>() where T : IMyInterface
{
return ((IdAttribute)typeof(T).GetCustomAttributes(typeof(IdAttribute), true)[0]).Id;
}
}
[Id("A")]
public class ImplA : BaseClass
{
}
[Id("B")]
public class ImplB : BaseClass
{
}
internal class Program
{
private static void Main(string[] args)
{
var val1 = BaseClass.GetId<ImplA>();
var val2 = BaseClass.GetId<ImplB>();
Console.ReadKey();
}
}
Here is my code (just a snippet to expose the problem) :
public class A
{
class B
{
//private class
}
public int nb;
}
Im tired but why can't I access to "nb" in my private class ?
You're gonna need an instance of A in order to access the instance member nb:
public class A
{
class B
{
public B()
{
A a = new A();
int nb = a.nb;
}
}
public int nb;
}
It's possible in java but not in C#.
You need to pass an instance of A to B.
In C# an 'outer' class is just a 'namespace' to the inner class. So the outer class is not being instantiated.
You need to pass an instance of A to B, like so:
public class A
{
class B
{
private A _outerClass;
public B(A outerClass)
{
_outerClass = outerClass;
// Then you can access nb thus:
_outerClass.nb;
}
}
public int nb;
}
I have some doubt to implementation of class and interface
I have 2 class like this
Public Class A:IFinal
{
private string name=string.Empty;
A()
{
name = "Pankaj";
}
public string MyName()
{
return name;
}
public string YourName()
{
return "Amit";
}
}
Public Class B:IFinal
{
private string name=string.Empty;
B()
{
name = "Amit";
}
public string GetNane()
{
return name;
}
public string YourName()
{
return "Joy";
}
}
Question:
Now i have a interface IFinal and i want to implement this interface in class A & B for method YourName() like this
public interface IFinal
{
string YourName();// Class A & Class B
}
Is it possible to implement on this way? if yes then How can i declare YourName() in interface and how can i use this?
Is it possible to declare virtual method in interface?like in class A & B we have a virtual method which need to be declare in interface.
You can make the method virtual in your implementation eg:
interface IFinal
{
string YourName();
}
class A: IFinal
{
public virtual string YourName() { return "Amit"; }
}
class B: IFinal
{
public virtual string YourName() { return "Joy"; }
}
Or you could use a common base implementation which both A and B derive from, eg
interface IFinal
{
string YourName();
}
abstract class FinalBase : IFinal
{
public virtual string YourName() { return string.Empty; }
}
class A : FinalBase
{
public override string YourName()
{
return "A";
}
}
class B : FinalBase
{
public override string YourName()
{
return "B";
}
}
class C : A
{
public override string YourName()
{
return "C";
}
}
new A().YourName(); // A
new B().YourName(); // B
IFinal b = new B();
b.YourName(); // B
FinalBase b = new C();
b.YourName(); // C
Pankaj - the code formatting and values in the IFinal are making it pretty hard to figure out what you're attempting to do. based on what is supplied, then the sample simply would not compile for the obviuos reason that you've got the same property (string YourName();) defined twice.
can you redo the question to clarify your intentions plz...
thanks
[edit] - i think i maybe 'understand' what you're asking - i.e. HOW to define the interface. here you go:
public interface IFinal
{
string YourName{ get; set; }
}
then, declare your variables along the lines of:
IFinal classA = new A();
IFinal classB = new B();
then, party hard :)
If you declare your interface as
interface IFinal {
string YourName();
}
both classes will have to implement that function which I think is what you are asking.
You have the reverse view of an Interface. First you have to declare the method in the Interface and then you have to move to implementation in the Classes that implements the Interface. You have taken the other way.
First declare the methods in the Interface
interface IFinal {
string YourName();
}
Then
Public Class A:IFinal
{
public string YourName()
{
return "Amit";
}
}
and
Public Class B:IFinal
{
public string YourName()
{
return "Joy";
}
}
Here the Class A and B implements the interface IFinal and its method YourName().
To call the methods in the respective classes
IFinal clsA= new A();
IFinal clsB= new B();
If you're trying to make IFinal have two methods, one that returns YourName from class A and one that returns YourName from class B then you'll need to introduce a third class (let's call it C) and then change the YourName methods on IFinal to be distinct - you can't have two methods with exactly the same signature on an interface.
So:
public interface IFinal
{
string YourNameA();
string YourNameB();
}
public class C : IFinal
{
public A A {get; set;}
public B B {get; set;}
public string YourNameA()
{
return this.A.YourName();
}
public string YourNameB()
{
return this.B.YourName();
}
}
Now, having said that, I'm not really sure if that's what you're asking or if doing this makes sense. You'll have to let us know more detail about what you're trying to do.