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.
Related
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.
I seriously hope my title is clear enough. If it's not I'm happy to have better suggestions.
The situation is thus (variable types are just examples):
public abstract class A
{
public virtual string X(string arg)
{
return "blarg";
}
}
public class CommonProperties : A
{
public string foof { get; set;} = "widget";
public string yay { get; set; }
public override string X(string arg)
{
return base.X(arg);
}
}
public class B : CommonProperties
{
public string UniqueProperty1 { get; set; }
public override string X(string arg)
{
return base.X(arg);
}
}
public class C : CommonProperties
{
public string UniqueProperty2 { get; set; }
public override string X(string arg)
{
return base.X(arg);
}
}
class D : A
{
public override string X(string arg)
{
return base.X(arg);
}
}
}
I'm generalizing my problem. This is not my actual code.
The problem is that C# does not allow multiple inheritance for abstract classes, interfaces don't allow for default code (yet) nor do they allow for default initializers.
I'd like CommonProperties to be derived from the abstract class and the classes derived from it (classes B and C) to be able to directly access the original abstract class's implementation of the X function rather than the overriding CommonProperties implementation of it. I've tried doing base.base.X(arg) but that didn't work. The next best way would be to have classes B and C derived from both class A and class CommonProperties but C# doesn't allow this. Making class A an interface won't work because I have a large number of classes derived from it and that would mean I'd have to copy the needed code into every. single. one. I can't make CommonProperties an interface because of that restriction on default values. I could move the common properties into their derived classes but that defeats code reuse (I may need to add additional properties over time and that would mean updating would be slower and more prone to error, etc.)
I can't wait until C# 8.0 (theoretically) having a default implementation of functions. If I can get B and C to directly access the hidden A.X() function that is hidden by the CommonProperties.X() function that would be a good workaround. I suspect that latter solution is possible with reflection (in fact in my project the A class is doing just that so the topic isn't difficult for me), but I'd like to know if there was a more direct method.
Edit: Adding one more class to clarify the issue better. I forgot that CommonProperties was supposed to inherit from A and also show that other classes directly inherit from A.
You need to add a non virtual method to class A that calls the A.X implementation. The method name includes the class name, I used double underscore to separate method name and class name.
public abstract class A
{
public virtual string X(string arg)
{
return "blarg";
}
public string X__A(string arg)
{
return X(arg);
}
}
public class CommonProperties : A
{
public string foof { get; set;} = "widget";
public string yay { get; set; }
public override string X(string arg)
{
return "comarg";
}
}
public class B : CommonProperties
{
public string UniqueProperty1 { get; set; }
public override string X(string arg)
{
return X__A(arg);
}
}
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;
}
Is it possible to write a class that acts like the super class of two other classes.
For example I have class A and class B. A and B share similar properties, but since I did not code A or B they do not extend an interface or class. Is it possible for me to create this super class so that when I generalize my code it can handle class A or B.
If this super class could be created this is some of what I would like to do in my class
class A
{
string Name { get; set;}
//does stuff
//I can't change this class
}
class B
{
string Name { get; set;}
//does similar stuff
//I can't change this class either
}
class MyClass
{
//I would like to create a list that can include both class B and class A
List<(pseudo superclass of A and B)> list;
//Both class A and class B have a name, I would like to get the name given a type of A or B
public (pseudo superclass of A and B) GetName((pseudo superclass of A and B) AorB)
{
//Write that name to the console
Console.WriteLine(AorB.Name);
}
}
Is this kind of wrapping possible, or will I need to do more work inside of MyClass (such as overloading methods) in order to accomplish what I need.
I'd suggest,
1 Create an interface:
interface IWrapper
{
string Name { get; set; }
...
}
2 Create wrapper classes:
class WrapperA : IWrapper
{
private A _a;
public WrapperA(A a) { _a = a; }
public Name
{
get { return _a.Name; }
set { _a.Name = value; }
}
// other properties here
}
and likewise for a BWrapper around B.
Then you can create your class as:
class MyClass
{
List<IWrapper> list;
public string GetName(IWrapper aOrB)
{
Console.WriteLine(aOrB.Name);
}
}
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();
}
}