Multiple Interfaces - c#

I am trying to input 2 interfaces to a class so that I may return information from them, in this case, an age and a name. However I have run into a problem where my C1 class does not have a matching return type of int, and I don't understand what to do now as any examples I've seen only had 1 interface or multiple classes. Here is what I have so far:
interface IWhatsMyAgeAgain
{
int GetAge();
}
interface ISayMyName
{
string GetName();
}
class C1 : IWhatsMyAgeAgain, ISayMyName
{
public int Age;
public string Name;
public string GetName() {return Name;}
public int GetAge() {return Age;}
}
class Program
{
static void PrintInfo (IWhatsMyAgeAgain item, ISayMyName Item )
{
Console.WriteLine("Name: {0}, Age {1}", Item.GetName(), item.GetAge() );
}
static void Main()
{
C1 a = new C1() { Name = "Tom", Age = 29 };
Console.ReadLine();
}
}

IWhatsMyAgeAgain's GetAge method returns int but your class returns string, change it to this:
class C1 : IWhatsMyAgeAgain, ISayMyName
{
public int Age;
public string Name;
public string GetName() { return Name; }
public int GetAge() { return Age; }
}

Related

How to creat a method to sort a 1D array of different customers type?

public void sortByType(){}
what should i enter here if i have three types of customers different in the way they pay
I have a class customer that inhereted 3 other classes they have a name ,id ,balance and a name of the books array and the date of barrowing and returning how can i sort them by
types??
class Book
{
public string BName { get;set; }
public string Day { get;set; }
public string Month { get;set;} }
public string Year { get;set;} }
public override string ToString(){}
}
then I created an abstract class Customer
abstract class Customer
{
protected string name;
protected double balance;
protected double ID_num;
protected Book[] rental_books = new Book[3];
public string Name { get { return name; } set { name = value; } }
public double Balance { get { return balance; } set { balance = value; } }
public double ID_NUM { get { return ID_num; } set { ID_num = value; } }
public override string ToString() {}
public abstract void BarrowBook(string bn, string d, string m, string y);
public abstract void ReturnBook(string bn, string d, string m, string y);
public abstract void AddToBalance(double sum);
}
and inherted it to the other three child classes and add what I need to each method
class NormalCustomer : Customer{}
class MemberCustomer : Customer{}
class StudentCustomer : Customer{}
then I created a library class
class Library
{
private Customer[] customers;
private int MaxCust=0;
private int count = 0;
public Library(int MaxCust) { this.MaxCust = MaxCust; }
public void Add(Customer c) { customers[count++] = c; }
public void ToString() {
public void SortByBalance()
{
double hold;
for (int i = 0; i < customers.Length - 1; i++)
for (int k = 0; k < (customers.Length - 1) - i; k++)
{
if (customers[k].Balance > customers[k + 1].Balance)
{
hold = customers[k].Balance;
customers[k].Balance = customers[k + 1].Balance;
customers[k + 1].Balance = hold;
}
}
}
}
so all i need now is the methode i mentioned above and how to creat it
let's take your classes
public class Customer { ... }
public class NormalCustomer : Customer{}
public class MemberCustomer : Customer{}
public class StudentCustomer : Customer{}
Providing an array which contains all the children in a mixed order:
Customer [] array = new Customer[]
{
new StudentCustomer(),
new MemberCustomer(),
new NormalCustomer(),
new MemberCustomer(),
new StudentCustomer(),
new StudentCustomer(),
new NormalCustomer(),
};
You can use the method: OfType to extract the individual types:
var children_1 = array.OfType<NormalCustomer>();
var children_2 = array.OfType<MemberCustomer>();
var children_3 = array.OfType<StudentCustomer>();
Now you simply need to concatenate them into a single collection using the Concat method. It expects that the second collection contains the same type of elements so you need to cast it temporarily to the parent type:
Customer [] sorted children_1.Cast<Customer>().Concat(children_2).Concat(children_3).ToArray();

Change a static variable in a subclass without changing it in the parent class

I want that a.ID() returns 0 and b.ID() returns 1 and here is my code:
public class A {
public static int id;
public int ID() {return id;}
}
public class B : A { }
public class Main {
void Program() { //This executes when I execute the program
A.id = 0;
B.id = 1;
}
}
But it doesn't work, this also doesn't work:
public class A {
public static int id;
public int ID() {return id;}
}
public class B : A {
public new static int id; //id is actually 1 but ID() is still 0
}
public class Main {
void Program() { //This executes when I execute the program
A.id = 0;
B.id = 1;
}
}
How can I fix this?
You can create two static variables and one virtual property
public class A
{
private static int _idA;
public virtual int Id
{
get { return _idA; }
set { _idA = value; }
}
}
public class B : A
{
private static int _idB;
public override int Id
{
get { return _idB; }
set { _idB = value; }
}
}
Or one property and use new keyword to override it
public class A
{
public static int Id { get; set; }
}
public class B : A
{
public static new int Id { get; set; }
}
To test first solution you can try following
static void Main(string[] args)
{
A test = new B();
new B().Id = 3;
new A().Id = 2;
test.Id = 1;
Console.WriteLine(test.Id + " " + new B().Id + " " + new A().Id);
Console.ReadKey();
}
If you can accept these rules:
The numbers can be anything, ie. any legal int
They don't have to start at 0
They don't have go up by 1 for each new unique type
The numbers are allowed to change between executions of your program
ie. you run your program and type A returns id 33554436
You change the program (somewhere else) and rerun, now type A returns id 33554437 (a different value)
then here is a way to get your ID:
public class Base
{
public int ID
{
get
{
return GetType().MetadataToken;
}
}
}
You don't need to override this property to get unique id's for each type but you can no longer guarantee what the values will be, here's example output from two such derived classes:
33554436
33554437
If I added a new type between those two and reran, I got:
33554436
33554438
If you're afraid the constant trip to reflection is going to be expensive here is an alternative declaration:
public class Base
{
private readonly Lazy<int> _ID;
protected Base()
{
_ID = new Lazy<int>(() => GetType().MetadataToken);
}
public int ID
{
get
{
return _ID.Value;
}
}
}
You can make the ID method virtual and override it in the B class like this:
public class A
{
public static int id;
public virtual int ID() { return id; }
}
public class B : A
{
public static int id;
public override int ID()
{
return id;
}
}
Here is another way to do it that uses Reflection:
public class A
{
public static int id;
public int ID()
{
return (int)this.GetType()
.GetField("id", BindingFlags.Static | BindingFlags.Public)
.GetValue(null);
}
}
public class B : A
{
public static int id;
}
This way, you don't have to override the ID method on each subclass. However, you still need to defined a static id field in each subclass.

Class placing a instance of its self in static list located in the class

Is this a common way to store instances in a list that can be accessed by any class. Are there any better Techniques to achieving this?
class fish
{
string species = "Gold Fish";
int age = 1;
public static list<fish> Listholder = new list<fish>();
Listholder.add(this);
}
List<T> is not thread safe, so if you want to add/remove fishs from different threads you should use ConcurrentBag<T> instead.
For example:
public class Fish
{
public string Species { get; set; }
public int Age { get; set; }
private static System.Collections.Concurrent.ConcurrentBag<Fish> Aquarium = new System.Collections.Concurrent.ConcurrentBag<Fish>();
static Fish()
{
var goldFish = new Fish { Age = 1, Species = "Gold Fish" };
PutFishIntoAquarium(goldFish);
}
public static void PutFishIntoAquarium(Fish fish)
{
Aquarium.Add(fish);
}
public static void ClearAquarium()
{
Fish someFish;
while (!Aquarium.IsEmpty)
{
TryTakeFishOutOfAquarium(out someFish);
}
}
public static bool TryTakeFishOutOfAquarium(out Fish fish)
{
if (Aquarium.TryTake(out fish))
return true;
return false;
}
public static bool TryLookAtSomeFish(out Fish fish)
{
if (Aquarium.TryPeek(out fish))
return true;
return false;
}
}
I think what you're trying to get at is a way to store a globally accessible list of fish somewhere. I.e. to have a central repository of fish that all other classes get their fish from.
If this is so, there are other ways of doing this such as the Service/Repository pattern. Keep in mind that having a mutable public static field will make testing and re-usability harder.
a Class has Properties.
the class allows you to create objects.
class fish()
{
Private String _Type;
Private Int _Age;
Private String _Species;
Public Type
{
get _Type;
set _Type = Value;
}
Public Age
{
get _Age;
set _Age = Value;
}
Public Species
{
get _Species;
set _Species = Value;
}
public new(string Type, Int Age, String Species)
{
this.Type = Type;
this.Age = Age;
this.Species = Species;
}
}
//this is your new object.
Fish SunFish = New Fish("small", 9, "Sunfish");
after creating an object you can create a list of objects

How do i use this class in the main function? Dictionaries and indexers (Collections)

I am trying to add entries in dictionary array list but i don't know which arguments to set in the People Class in the main function.
public class People : DictionaryBase
{
public void Add(Person newPerson)
{
Dictionary.Add(newPerson.Name, newPerson);
}
public void Remove(string name)
{
Dictionary.Remove(name);
}
public Person this[string name]
{
get
{
return (Person)Dictionary[name];
}
set
{
Dictionary[name] = value;
}
}
}
public class Person
{
private string name;
private int age;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
}
using this seem to give me error
static void Main(string[] args)
{
People peop = new People();
peop.Add("Josh", new Person("Josh"));
}
Error 2 No overload for method 'Add' takes 2 arguments
This peop.Add("Josh", new Person("Josh"));
should be this
var josh = new Person() // parameterless constructor.
{
Name = "Josh" //Setter for name.
};
peop.Add(josh);//adds person to dictionary.
The class People has the method Add which only takes one argument: a Person object. The Add on the people class method will take care of adding the it to the dictionary for you and supplying both the name (string) argument and the Person argument.
Your Person class only has a parameterless constructor, which means that you need to set your Name in the setter. You can do this when you instantiate the object like above.
For your design this would solve the problem:
public class People : DictionaryBase
{
public void Add(string key, Person newPerson)
{
Dictionary.Add(key , newPerson);
}
public void Remove(string name)
{
Dictionary.Remove(name);
}
public Person this[string name]
{
get
{
return (Person)Dictionary[name];
}
set
{
Dictionary[name] = value;
}
}
}
public class Person
{
private string name;
private int age;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
}
And in Main:
People peop = new People();
peop.Add("Josh", new Person() { Name = "Josh" });

LinFu - can't quite see how to do what I want

Just found LinFu - looks very impressive, but I can't quite see how to do what I want to do - which is multiple inheritance by mixin (composition/delegation as I'd say in my VB5/6 days - when I had a tool to generate the tedious repetitive delegation code - it was whilst looking for a C# equivalent that I found LinFu).
FURTHER EDIT: TO clarify what I mean by composition/delegation and mixin.
public class Person : NEOtherBase, IName, IAge
{
public Person()
{
}
public Person(string name, int age)
{
Name = name;
Age = age;
}
//Name "Mixin" - you'd need this code in any object that wanted to
//use the NameObject to implement IName
private NameObject _nameObj = new NameObject();
public string Name
{
get { return _nameObj.Name; }
set { _nameObj.Name = value; }
}
//--------------------
//Age "Mixin" you'd need this code in any object that wanted to
//use the AgeObject to implement IAge
private AgeObject _ageObj = new AgeObject();
public int Age
{
get { return _ageObj.Age; }
set { _ageObj.Age = value; }
}
//------------------
}
public interface IName
{
string Name { get; set; }
}
public class NameObject : IName
{
public NameObject()
{}
public NameObject(string name)
{
_name = name;
}
private string _name;
public string Name { get { return _name; } set { _name = value; } }
}
public interface IAge
{
int Age { get; set; }
}
public class AgeObject : IAge
{
public AgeObject()
{}
public AgeObject(int age)
{
_age = age;
}
private int _age;
public int Age { get { return _age; } set { _age = value; } }
}
Imagine objects with many more properties, used in many more "subclasses" and you start to see the tedium. A code-gernation tool would actually be just fine...
So, LinFu....
The mixin example below is fine but I'd want to have an actual Person class (as above) - what's the LinFu-esque way of doing that? Or have I missed the whole point?
EDIT: I need to be able to do this with classes that are already subclassed.
DynamicObject dynamic = new DynamicObject();
IPerson person = null;
// This will return false
bool isPerson = dynamic.LooksLike<IPerson>();
// Implement IPerson
dynamic.MixWith(new HasAge(18));
dynamic.MixWith(new Nameable("Me"));
// Now that it’s implemented, this
// will be true
isPerson = dynamic.LooksLike<IPerson>();
if (isPerson)
person = dynamic.CreateDuck<IPerson>();
// This will return “Me”
string name = person.Name;
// This will return ‘18’
int age = person.Age;

Categories