I have created a simple test project to use a class as a custom List type and have a couple of questions regarding the use of different syntax when declaring variables.
I have a class called CustomerInfo which defines all the variables required to be stored for the customer information which will be added to a list as seen below:
protected string Firstname { get; set; }
protected string Surname { get; set; }
protected int Age
{
get
{
return Age;
}
set
{
if(value < 0)
{
throw new AgeException("Age cannot be a value below 0");
}
else
{
Age = value;
}
}
}
protected string Gender { get; set; }
Questions:
1) Why does the code below not allow me to access the protected variables in the CustomerInfo class even though I am inheriting the class?
class Program : CustomerInfo
{
static void Main(string[] args)
{
CustomerInfo custInfo = new CustomerInfo();
custInfo.Firstname = "Richard"; //not working
custInfo.Surname = "Smith"; //not working
List<CustomerInfo> custList = new List<CustomerInfo>();
custList.Add(custInfo);
}
}
2) When looking at Windows Forms applications they already contain an inheritence of Form in the code of any Form you create. If you have to inherit a class to access the protected variables & methods it has, how can you access the variables if each form already has an inheritance that you cannot remove?
Thanks
You are misunderstanding the purpose of inheritance. Inheritance is designed to represent a relationship between two objects where one is a more specialized version of the other. This is sometimes called an "is-a" relationship.
Consider the following class definitions:
class Fruit {}
class Apple : Fruit {}
class Banana: Fruit {}
In this case, Apple and Banana both inherit from Fruit to express the "is-a" relationship - a Banana is a Fruit. In object-oriented design, this allows you to write a method like this:
class Person
{
public void Eat(Fruit fruit) {}
{
// stuff goes here
}
}
The Eat method allows the Person class to eat anything that is a Fruit, including classes that derive from Fruit. So you can do the following:
Person person = new Person();
Apple apple = new Apple();
Banana banana = new Banana();
person.Eat(apple);
person.Eat(banana);
Compare this to the class definition you have written:
class Program : CustomerInfo
In the language of OOP, this says "a Program is a CustomerInfo." I don't think that's what you want. Using the protected keyword doesn't make sense here because your inheritance relationship doesn't make sense. If Program is supposed to be able to access CustomerInfo members, they should be declared public or internal.
The protected keyword is a member access modifier. A protected member
is accessible within its class and by derived class instances.
Source MSDN
CustomerInfo custInfo = new CustomerInfo();
custInfo.Firstname = "Richard"; //not working
custInfo.Surname = "Smith"; //not working
This code is not working because your custInfo's Firtsname and Surname are not accessible in the Program class. But you should be able to do the following, as your Program class is inherited from CustomerInfo :
Firstname = "Richard";
Surname = "Smith";
For the second question you can do something like the following:
Class1 : Form
{
// here will be your protected members
}
Class2 : Class1
Related
This question already has answers here:
Generating Interfaces from entity framework database first auto-generated code
(3 answers)
Closed 3 years ago.
Consider a function LengthOfName; it takes in an object which has a name property, and returns the length of it's name:
class Dog {
public string Name;
}
class Human {
public string Name;
}
class MainClass {
public static int LengthOfNameDog (Dog dog) {
return dog.Name.Length;
}
public static int LengthOfNameHuman (Human human) {
return human.Name.Length;
}
public static void Main (string[] args) {
var Fido = new Dog { Name = "Fido" };
var Alex = new Human { Name = "Alex" };
Console.WriteLine (LengthOfNameDog(Fido));
Console.WriteLine (LengthOfNameHuman(Alex));
}
}
This isn't great, as we have to repeat ourselves. I understand that there is already a standard way around this, namely to have Dog and Human inherit from a single class, for instance:
class ThingWithName {
public string Name;
}
class Dog : ThingWithName {}
Which is fine. The problem I'm having is that I'm using class definitions which are auto-generated from Entity Framework, so I don't think I'd want to mess with their class to say they inherit from some master class.
What I'd like to be able to do is to implement a function which takes in an instance of any object which has given properties, in the example above, for instance, any object which has the Name property.
Is this possible in c#?
Since Entity Framework generates partial entity classes, you can define an interface with a Name property and create another partial class for each entity type that implements this interface:
public interface IHasName
{
string Name { get; }
}
public partial class MyEntity : IHasName {}
public partial class MyOtherEntity : IHasName {}
public static int LengthOfNameHuman (IHasName entity) {
return entity.Name.Length;
}
If the entities don't share a common base class or interface, you'll have to use reflection to get the Name property.
class TestA{
some code.....
}
class TestB{
.....
}
class Program{
void Main(){
TestA obj= new TestB();////When and why do we sometimes do this?
}
}
What are the different scenarios when we would have to refer one object to another class?
We don't. We created a variable called obj, and declared the variable to be of type TestA. That means that that variable can contain a reference to any object this IS-A TestA.
You then create a TestB object. Presumably, TestB derives from TestA, which is not shown in your question. But that means that this new object, is, generally, a TestA, as well as being, specifically, a TestB. We then assign a reference to this object to the obj variable.
Which is fine. It still is a TestB object. It's just that this code, clearly, doesn't intend to use any of it's B-ish nature. Just the core A-ish part that it shares; It's also possible that the TestB class overrides some of TestA's members, in which case it will still demonstrate it's B-ish nature when those members are accessed.
From your code example this approach could be used if TestB inherits from TestA. If you're unsure what inheritance is you should read a bit about Object Oriented programming. Another approach where you would have a class which creates other objects is if you are using a Factory Pattern. There's plenty of information on the web about this pattern too. If you are using a factory pattern you wouldn't use the same constructor approach as in your code though (i.e. you wouldn't expect a new instance of an object to return a different object.)
the answer to this as much as i know, this could be in two cases:
1-Polymorphism.
2-Interfaces.
I'll show u how:
Polymorphism is like :
//an example of Polymorphism.
class FamilyMembers //parent class
{
public virtual void GetData() //it's virtual method cuz it can be overridden later
{
Console.WriteLine("Family");
}
}
class MyBrother : FamilyMembers //child class
{
public override void GetData() //the same method that we wrote before has been overridden
{
Console.WriteLine("Bro");
}
}
class Program
{
static void Main(string[] args)
{
//here's what u asking about
FamilyMembers myBrother = new MyBrother(); //MyBrother is a family member, the system now will choose the GetData() method from the child class MyBrother
myBrother.GetData();
Console.ReadLine();
}
}
Interface is like:
public interface IFamily //the Parent Class
{
//an interface holds the signature of it's child properties and methods but don't set values
//Some properties signatures
int Age { get; set; }
string Name { get; set; }
//some methods
void PrintData();
}
public class MyBrother : IFamily //Child class that inherits from the parent class
{
//some properties, methods, fields
public string Name { get; set; } //public required
public int Age { get; set; } //public required
private string Collage { get; set; } //for my brother only
//constractor that sets the default values when u create the class
public MyBrother()
{
Name = "Cody";
Age = 20;
Collage = "Faculty of engineering";
}
////a method
void IFamily.PrintData()
{
Console.WriteLine("Your name is: " + Name + " and your age is: " + Age + " and you collage is: " + Collage);
}
}
class Program
{
static void Main(string[] args)
{
//now let's try to call the the methods and spawn the child classes :)
//spawn the child class (MyBrother) that inherits from the Family interface
//this is the answer of ur question
IFamily myBrother = new MyBrother(); // the constructor will auto-set the data for me so i don't need to set them
//printing the dude
myBrother.PrintData();
Console.ReadLine();
}
}
I hope this will do :)
We can only do this when class have parent-child relationship,Otherwise it can't be possible to assign one class memory to another class.
Read More...1
Read More...2
So I'm used to working with javascript, and being able to simply do
dog={};
dog.name="Rex";
dog.examine=function(){console.log("This is a dog. Its name is "+this.name+".");}
cat={};
cat.name="Phil Collins";
cat.examine=function(){console.log("This is a cat. Its name is "+this.name+".");}
dog.examine();
cat.examine();
This would return, of course : This is a dog. Its name is Rex. and This is a cat. Its name is Phil Collins.
I've started learning xna, and I'm very confused by this whole lambda/delegate/action system. I'm not sure what syntax to use, the compiler gets angry when I try to make a function with no input or output variables, and I'm having trouble keeping the proper scope for this. Could someone please help me find out how I'd port the above code into c#?
I made this a Community Wiki because this question is really too broad, C# and JavaScript are very different things and answer can't be complete. I'll just sketch a direction but the way to go is to learn C# and differences will be clear. That's the reason I'll try to first write something similar to JavaScript program you posted and then, step by step, to change it to be more C# style.
Let me also say that if you extensively want to use dynamic typing in C# (or JavaScript programming style) then (probably)...you picked wrong language.
Step 1
Something somehow close to what you write can be written in C# like this (let me use this example to highlight differences, you really have to buy a good C# book and start from there):
dynamic dog = new ExpandoObject();
dog.Name = "Pluto";
dog.Hello = new Action(() => Console.WriteLine("This is a dog named {0}", dog.Name));
dog.Hello();
First of all you see that in C# a variable must be typed, in this case with dynamic we bypass static typing and we may even change content later (but this is another story). ExpandoObject is a special object that can be expanded adding properties, it's not normal C# behavior where almost everything about types is checked at compile-times (don't think about casts, now).
Second line is pretty similar, nothing new (for you) here but pretty strange if you're a traditional C# programmer.
Finally the interesting part: we add a property that is a delegate (using a lambda) but here there is a big difference (you also noted by yourself): this has a different meaning in C# and within a method this is the instance of the object where method is declared (OK it's declared in the class but you know what I mean). Let's watch this: dog.Name, we captured dog variable inside our anonymous method (as you would do in JavaScript).
Step 2
It's just a starting point because design and philosophy is completely different, same thing in C# should be done with an Animal base class and Dog + Cat derived classes but you'll learn this by yourself. Let me do just one more simple step in that direction:
var typedDog = new {
Name = "Pluto",
Hello = new Action(() => Console.WriteLine("This is a dog named {0}", Name))
};
typedDog.Hello();
Maybe you don't see such big difference but this code is strongly typed! What does it means? We declared an anonymous class with two properties and one of them is a delegate, we still can't use this and in C# (unlike Java) we can't declare methods in anonymous types but now compiler knows (then it's compile-time) what things are. For example:
dog.Name = 2; // Valid, now Name is an integer
dog.Hello = 2; // Valid, also Hello is an integer
dog.Hello(); // This will fail at run-time because Hello now isn't a delegate
Is it bad, right? With our new typed object this isn't possible:
typedDog.Name = 2; // Compile-time error, Name is a string
typedDog.Hello = 2; // Compile-time error, Hello must be an Action delegate
Of course we can assign a new anonymous delegate to replace old one (but type must match):
typedDog.Hello = new Action(() => Console.WriteLine("This is a typed dog named {0}", typedDog.Name));
Step 3
This has been extensively described in other answers so I won't repeat, just to sketch things:
class Animal {
public string Name { get; set; }
public abstract void Hello();
}
class Dog : Animal {
public override void Hello() {
Console.WriteLine("This is a dog named {0}", this.Name);
}
}
Note that now you finally have this pointer and it does what you expect. It's used like this:
var dog = new Dog { Name = "Pluto" };
dog.Hello();
Note that in JavaScript you can even write this:
var anInteger = 2;
anInteger.PrintSomething();
That's not allowed in C# because at compile-time (unless you use dynamic variables) it needs to know if PrintSomething() is a method and how to call it. Same thing can be also done like this (using interfaces):
class IPolite {
void Hello();
}
class Dog : IPolite {
public string Name { get; set; }
public void Hello() {
Console.WriteLine("This is a dog named {0}", this.Name);
}
}
Now you can even have a completely different object:
class Car : IPolite {
public string Name { get; set; }
public void Hello() {
Console.WriteLine("This is a car, name is {0}", this.Name);
}
}
It can be used like this:
IPolite thing = new Dog { Name = "Pluto" };
thing.Hello();
thing = new Car { Name = "Ferrari F50" };
thing.Hello();
Please note we're reusing same thing variable. Many other things to see and to do...
In general C# and other strongly-typed languages are VASTLY different from script / run-time languages like JS. C# is a compiled language and this "strongly-typed" nature is ensured by the compiler. This is true for many type-safe (http://en.wikipedia.org/wiki/Type_safety) languages.
Generally speaking a class structure in C# would look like this:
public abstract class Animal {
//Fields or instance variables are typically hidden from the outside world (consuming code). This is controlled by the 'access-modifier' in this case, private.
private string _name;
//Constructor is called when you use the 'new' keyword to instantiate an instance of a type that derives from Animal (Animal cannot be instantiated directly because it is abstract).
protected Animal() {
//Avoids null references unless someone overrides the property setter, for this example, it's safe enough
_name = string.Empty;
}
//This is syntax for declaring a property
//properties are publicly accessible pieces of data that control access to a basic
// field (variable).
// It allows you to apply logic to the field it wraps.
// In this example, the field cannot be set to a null or empty string (except by the constructor, which bypasses the property.
public virtual string Name {
get {
return _name;
} set {
if(!String.IsNullOrWhiteSpace(value)) {
_name = value;
}
}
} // end property Name
//This is a method that must be overridden by any derived type that is not abstract and may (or may not) be overridden by a derived type that is abstract.
public abstract void Examine();
}
public class Cat : Animal {
public Cat : base() {}
public override void Examine() {
Console.WriteLine(String.Concat("This is a cat. It's name is ", this.Name, "."));
}
}
public Class Dog : Animal {
public Dog() : base() {}
public override void Examine() {
Console.WriteLine(String.Concat("This is a dog. It's name is ", this.Name, "."));
}
}
//In some runnable code elsewhere like a console application:
Animal cat = new Cat() {Name = "Mittens"};
Animal dog = new Dog() {Name = "Fido"};
cat.Examine();
dog.Examine();
For more information about access modifies, see here:http://msdn.microsoft.com/en-us/library/wxh6fsc7.aspx
You could use inheritance to accomplish it:
public class Animal
{
public string Name { get; private set; }
public Animal(string name)
{
this.Name = name;
}
public void Examine()
{
Console.WriteLine("This is a {0}. Its name is {1}.", this.GetType(), Name);
}
}
public void Dog : Animal
{
public Dog(string name) : base(name) { }
}
public void Cat : Animal
{
public Cat(string name) : base(name) { }
}
Then you can create instances of these derived types:
static class Main(string[] args)
{
Dog rex = new Dog("rex");
Cat phil = new Cat("Phil Collins");
rex.Examine();
phil.Examine();
}
Here's a simple example. I'd strongly suggest picking up a book or checking out a tutorial because this stuff will be covered pretty early on.
public abstract class Animal
{
public string Type { get; private set; }
public string Name { get; set; }
protected Animal(string type)
{
Type = type;
}
public virtual string Examine()
{
return string.Format("This is a {0}. Its name is {1}.", Type, Name);
}
}
public class Dog : Animal
{
public Dog() : base("Dog")
{
}
}
public class Cat : Animal
{
public Cat() : base("Cat")
{
}
}
var dog = new Dog { Name = "Rex" };
var cat = new Cat { Name = "Phil Collins" };
You can use the so-called anonymous functions or you could make this examine function of yours to be a property of type Action. For e.g., you could write:
Animal.cs:
public abstract class Animal
{
public string Name { get; set; }
public Action Examine { get; set;}
}
Dog.cs:
public class Dog : Animal
{
}
Cat.cs:
public class Cat : Animal
{
}
And then, somewhere where you could use this, you can say:
Dog dog = new Dog { Name = "Rex" };
dog.Examine = delegate
{
Console.WriteLine("This is a dog. Its name is {0}.", dog.Name);
};
Cat cat = new Cat { Name = "Phil Collins" };
cat.Examine = delegate
{
Console.WriteLine("This is a cat. Its name is {0}.", cat.Name);
};
dog.Examine();
cat.Examine();
Bear in mind that instead of using 'this', you're using a reference to the previously instantiated class which extends Animal (Dog or Cat).
There's also the other option... Combining ExpandoObject class and a dynamic keyword:
dynamic dog = new ExpandoObject();
dog.Name = "Rex";
Action examineDog = delegate {
Console.WriteLine("This is a dog. Its name is {0}.", dog.Name);
};
dog.Examine = examineDog;
dynamic cat = new ExpandoObject();
cat.Name = "Phil Collins";
Action examineCat = delegate
{
Console.WriteLine("This is a cat. Its name is {0}.", cat.Name);
};
cat.Examine = examineCat;
dog.Examine();
cat.Examine();
Hi My code is as follows
public partial class Class1:InheritBase1
{
public Class1()
{
//Access table1 here
}
}
public class InheritBase2
{
protected DataTable table1{get;set;}
}
I need to access table1 from InheritBase2 class to my class.
As C# doesn't allow multiple inheritance what are the possible ways to achieve this ?
Thank's all.
You could easily solve this using composition instead of inheritance.
Say there's a class A and a class B. A has a B.
public class A
{
public B AssociatedB { get; set; }
}
Why...?
could you please elaborate – kyle
In object-oriented programming there're two approaches to create relationships between objects. Either of them are necessarily hierarchical.
If you end up thinking some object is something, we'll be talking about inheritance. For example, a cat is an animal. That is, a class cat derives from animal.
In the other hand, if you end up thinking some object has a X thing, we'll be talking about composition. For example, a car has an engine.
At the end of the day, if you are using inheritance in order to share a reference to a DataTable, I really encourage you to use composition instead, because your class has a DataTable:
public class A
{
public DataTable Table { get; set; }
}
public class B
{
public DataTable Table { get; set; }
}
DataTable someTable = new DataTable();
// Both class instances share the same DataTable
// because you set the same object to both
// class properties
A someA = new A();
someA.Table = someTable;
B someB = new B();
someB.Table = someTable;
You can benefit form the composition.
class A : B {
}
can be replaced as
class A {
B b
}
If you want that A and B can be used in the same contenxt you need to intruduce a interface.
The interface allow you to define abstract functionality and have various implementations for it.
interface ISampleInterface
{
void SampleMethod();
}
In case when we have
class B : ISampleInterface
{
void SampleMethod() {
//Do some action
}
}
Now your class A can or inherit form B in odrder to access to sample method or use composition.
class A : ISampleInterface {
B b;
void SampleMethod() {
b.SampleMethod();
}
}
Then i code you can use this like
ISampleInterface sa = new A();
ISampleInterface sb = new B();
sa.SampleMethod(); //Call B through A
sb.SampleMethod(); //Call B
This is only bired description for more you should follow a tutorial about Object Oriented Programming.
I have a class that has private fields... (cars)
I then inherit from this class... (Audi)
In the (Audi) class, when I type this. in the constructor...
the private fields are not available...
Do I need to do anything special to expose this private fields in (cars) class so that they are accessible via this. in (Audi class)?
One (bad) option is to make the fields protected - but don't do this; it still breaks proper encapsulation. Two good options:
make the setter protected
provide a constructor that accepts the values
examples:
public string Name { get; protected set; }
(C# 2.0)
private string name;
public string Name {
get { return name; }
protected set { name = value; }
}
or:
class BaseType {
private string name;
public BaseType(string name) {
this.name = name;
}
}
class DerivedType : BaseType {
public DerivedType() : base("Foo") {}
}
Philippe's suggestion to declare the fields as protected instead of private will indeed work - but I suggest you don't do it anyway.
Why should a derived class care about an implementation detail of how the data is stored? I suggest you expose protected properties which are (currently) backed by those fields, instead of exposing the fields themselves.
I treat the API you expose to derived classes as very similar to the API you expose to other types - it should be a higher level of abstraction than implementation details which you may want to change later.
You should declare them as "protected" instead of private
You are probably looking for a concept called constructor inheritance. You can forward arguments to the base classes constructor - see this example, where the Audi has a flag indicating whether it's an S-Line edition or not:
namespace ConstructorInheritance
{
abstract class Car
{
private int horsePower;
private int maximumSpeed;
public Car(int horsePower, int maximumSpeed)
{
this.horsePower = horsePower;
this.maximumSpeed = maximumSpeed;
}
}
class Audi : Car
{
private bool isSLineEdition = false;
// note, how the base constructor is called _and_ the S-Line variable is set in Audi's constructor!
public Audi(bool isSLineEdition, int horsePower, int maximumSpeed)
: base(horsePower, maximumSpeed)
{
this.isSLineEdition = isSLineEdition;
}
}
class Program
{
static void Main(string[] args)
{
Car car = new Audi(true, 210, 255);
// break here and watch the car instance in the debugger...
}
} }