Let say i have a base class
class baseClass
{ }
And another class that inherit from that baseClass
class foo : baseClass
{ }
I tryed to cast it back directly (baseClass)foo but the compiler say it cannot be done.
Is there a way from foo to get only the baseClass?
foo is a baseClass you don't need any casting. And your code should work without any problems:
var foo = new foo();
baseClass x = (baseClass) foo;
If you derive a class A from class B you can always refer to A as if it were B. Of course this is not true in the revese case. In general you can always refer down the chain of inherited classes.
If the compiler complain on such a thing, it could just mean you have several baseClass defined in several Namespace and you're actually not referencing the right baseClass.
Check your Namespaces it should solve your bug.
Here a working example with different Namespaces
namespace BaseNameSpace
{
public class BaseClass
{
public string Name { get; set; }
}
}
namespace TestNameSpace.Class
{
public class TestClass : BaseClass
{
public string Address { get; set; }
}
}
Use :
TestClass test1 = new TestClass();
BaseClass b = test1;
Ensure that there is the correct using :
using BaseNameSpace;
using TestNameSpace.Class;
Related
My question may be complicated , but I will try to explain it . Suppose that I have a Interface called IA and class called A ,
Interface IA:
public interface IA
{
public void Test();
}
Class A
public class A : IA
{
public string Name { get; set; }
public A()
{
}
}
When I'm trying to use Dependency injection :
Main Class :
public class MainClass
{
IA objectA = new A();
objectA.Name = "test A"; // Not working , I didn't get this Name and I can't find it .
}
IA does not contains a definition for Name ...
What's the reason of this problem?
I have created a Gist https://gist.github.com/ian-bowyer/f1a57a5fc8e4df41cc63d9816276d708 with the code on.
I changed IA to IApple and A to Apple.
The reason is that you have created an variable of type IApple (which then does not have the Name Property in it)
IA objectA = new A();
This says create me a variable called objectA of this interface IA using the constructor A(). The objectA will have the shape of the interface (IA) and not your A (object).
If you are wanting to have Name using the code then perhaps add it to the interface to make it available.
Why do you create a Instance of interface class?
Try to create Instance of Class A like:
public class MainClass
{
A objectA = new A();
objectA.Name = "test A";
}
So you can get your Test() Method and Name Property.
Or you put Name Property in Interface Class IA and all classes inherited from this Interface have Name Property.
I am working on Json Obejct deserielize to a class in .net VS2015 on win 7.
public class1
{
[JsonProperty(TypeNameHandling = TypeNameHandling.Objects)]
public Class1 data1;
public Class2 data2;
}
public abstract Class1
{
some functions
}
public subClass1 : Class1
{
public string myData1 { get; set; }
public string myData2 { get; set; }
}
In my code of deserierlizing:
var mo = MyObject as JObject;
ParentMyClass = mo.ToObject<MyClass>();
I know that an abstract class cannot be instantiated.
So, subClass1 (which is one of the implementation of Class1) is serialized.
But, subClass1 is null after deserialized.
Did I do something wrong ?
UPDATED:
because the code of the classes is too complex, I just simplified the logic.
When you call mo.ToObject<Class1>(); Newtonsoft.Json library will try to create an instance down the line. The problem is you cannot instantiate a abstract. You can see this your self by calling var x = new Class1(); somewhere in you code. This will give you error.
That being said, one thing you could do is create another class that inherits the abstract class.
public class NonAbstract : Class1 {}
this way you will have a class that can be instantiated. And then you can do this.
mo.ToObject<NonAbstract >();
I have two classes like Class A and Class B. Class A have some properties, methods and Class B have only the properties. But both Classes have the same set of properties.
My Question is, If I add any new property in Class A, I need to add that in Class B also. If I did not add means, need to show error. How can I achieve this through C#?
You may achieve this by using an Interface and implementing it both in class A and class B. In the interface, define the property that is required in class A and B:
public interface ICommonProperty
{
string MyProperty{ get; set; }
}
Or you can use keyword abstract to create a class in common for A and B.
abstract class BaseClass // Abstract class
{
public int X {get;set;} // property in common for 2 class
}
class A : BaseClass
{
}
class B : BaseClass
{
public int Y {get;set;} // other property of B
}
You can go with the abstract class. The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
Here is a simple example related to your question However you can understand and learn about Abstract classes here : Abstract Class
using System;
public class Program
{
public static void Main()
{
A objA = new A();
objA.printA();
B objB = new B();
objB.printB();
}
}
abstract class Parent{
public int a = 5;
}
class A : Parent
{
public void printA()
{
Console.WriteLine("In class A, value is "+a);
}
}
class B : Parent
{
public void printB()
{
Console.WriteLine("In class B, value is "+a);
}
}
Output of the above program is:
In class A, vlaue is 5
In class B, vlaue is 5
Hope this helps you.
I have 2 classes:
public class Class1
{
private string Name1;
public Class1()
{
//How to get Name2 of the derived class?
}
}
public class Class2 : Class1
{
private string Name2 = "asd";
public Class2(){}
}
How to get Name2 of the derived class in the base constructor?
public class Class1
{
private string Name1;
public Class1()
{
class2 xxx = this as class2
if (class2 != null)
this.Name1 = xxx.Name2;
}
}
"this as class2" - is not null
This example is correct. The only thing is I don't know Derived class is Class2 or class3 or class4 .... I need universal code
You cannot (and more importantly, you should not) do that. When you are in the constructor of the base class, the subclass portion has not been initialized yet, so there is no way to get to the members of the subclass: quite simply, they do not exist yet.
Another problem is that the Name2 attribute may not be present in a subclass at all, even at the level fo the definition: I can derive Class3 from Class1, and give it Name3 attribute instead of Name2.
All this does not touch on such "insignificant" matters as breaking encapsulation: Name2 is a private member, which may be removed in the future implementations of the Class2.
The only way for the subclass to communicate things to superclass in a constructor is passing parameters. This would work:
public class Class1 {
private string Name1;
public Class1(string subclassName2)
{
// Subclass has passed its Name2 here
}
}
public class Class2: class1 {
private string Name2;
public Class2(string myName) : base(myName) {
Name2 = myName;
}
}
You can access the code in the derived class from the base class code, but only from within an object which is actually a derived class object, and then only if the methods involved are virtual methods.
If you have an object which is itself an instance of the base class, then from within that instance you cannot see derived class code from the base class .
example
public class Baseclass{
public void Foo()
{
Bar();
}
public virtual void Bar()
{
print("I'm a BaseClass");}}
public classs Derived: BaseClass{
public override void Bar()
{
print("I'm a Derived Class");}}
Main()
var b = new BaseClass();
x.Foo() // prints "I'm a BaseClass"
// This Foo() calls Bar() in base class
var d = new Derived();
d.Foo() // prints "I'm a Derived Class"
// in above, the code for Foo() (in BaseClass)
// is accessing Bar() in derived class
I think you could not because when you instantiate derived class, base class constructor is called first to initialize base class and then the derived class is initialized.Within the base class constructor there is no way to access derived class members because they are not available at that time.
You cannot do it. It strictly violates the Object Oriented Approach programming ground rules.
As each instance of Class2 will have the Name2 property. But the same cannot be guaranteed for instance of object for Class1.
It's not really clear what you're trying to achieve. It is possible to do the following, but I don't think it's good practice:
interface IHasName2
{
string Name2 { get; }
}
class Class1
{
string Name1;
public Class1()
{
var withName2 = this as IHasName2;
if (withName2 != null)
{
Name1 = withName2.Name2;
}
}
}
Then classes deriving from Class1 may implement IHasName2 if they like.
But maybe you want an abstract class to make sure derived classes specify a Name2. It could be like this:
abstract class Class1
{
string Name1;
// instance property required to be implemented by deriving classes
protected abstract string Name2 { get; }
// instance constructor
protected Class1()
{
// 'Name2' can be read already here (dangerous?)
Name1 = Name2;
}
}
Finally, consider the simple solution proposed by dasblinkenlight to have the instance constructors of Class1 take in a string parameter for the name. Deriving classes would then have to supply that name parameter when they "chain" their base class constructor.
I want to force any class not to be able to create a new instance if it inherits a specific base class, so how this base class should look like?
The following code is in java. just to give you an Example
Base class has an exception on the constructor.
public class BaseClass
{
public BaseClass()
{
throw new AssertionError();
}
}
The child class extending the base class but if you create an object of it it will give u an exception.
public class MainClass extends BaseClass
{
public MainClass()
{
}
public static void main(String[] args) {
MainClass c = new MainClass();
}
}
You want to seal your base class.
public sealed class BaseClass
{
public BaseClass(){};
}
public class SubClass : BaseClass
{
public SubClass(){};
}
This will throw a compiler error because you cannot inherit from a sealed base.
You can't specify that in the baseclass, any deriving class is self responseable, if it wants to present the ability to be derived from, than you can't do anything about it.
you can declare the base class as const - that way other classes cant extend it.
You can't do this. Please specify why you want to do this.