Need help to understand polymorphism - c#

The classes below consist of
A - father class
B - Child class
Holder - Contains a list of A's
I want to reach a child property from the list of fatherobjects. Why cant I do this? Or better question, how do I do this?
public class A
{
public int var = 0;
}
public class B : A
{
public int Property1 { get; set; }
public int Property2 { get; set; }
public B()
{
}
public B(B p_B)
{
Property1 = p_B.Property1;
Property2 = p_B.Property2;
}
}
class Holder
{
private List<A> m_Objects = new List<A>();
public void AddObject(A p_Object)
{
m_Objects.Add(p_Object);
}
public void AddObjectProperty1(B p_B)
{
// At this point, m_Objects holds a B-object. And I want to add the value from Property1
// but there is no Property1 in the A-class so I cant do this. How do I use the base.values from
// a statement like the one below?
int index = m_Objects.FindIndex(item => item.Property1 == p_B.Property1);
if (index > -1)
m_Objects.ElementAt(index).Property1 += p_B.Property1;
}
}
class Program
{
static void Main(string[] args)
{
// Class to hold the objects
Holder h = new Holder();
// Create a B object
B b = new B();
b.Property1 = 1;
b.Property2 = 2;
// Place a new instance of the B-object in a list of A's
h.AddObject(new B(b));
// Add the value from Property1 to the value in the b-object in the a-list. :P
h.AddObjectProperty1(b);
Console.WriteLine(++b.var);
Console.ReadLine();
}
}

You can use type casting:
(m_Objects[i] as B).Property1
Or
((B)m_Objects[i]).Property1

At compile-time there is no possibility for the compiler to know, you would only add Bs to your list of As. So there is no guarantee whatsoever that each item in the following query is an instance of B and thus has Property1
int index = m_Objects.FindIndex(item => item.Property1 == p_B.Property1);
First possibilty is casting as in Artyom's answer. But this will fail if you not all of the elements in the List are really Bs. So if you rely on all Elements in m_Objects to be instances of B, why don't you just use List<B> m_Objects?
If you need the mixed list, you have to do a type-check in the query to ensure, you are dealing with an instance of Bbefore casting.
int index = m_Objects.FindIndex(item => (item is B) && (item as B).Property1 == p_B.Property1);
See this DotNetFiddle Example

Related

How would I find the value of an unspecified variable in other objects of the same class? C#

I want this method to work with any variable - i.e., passing a "Price" value to the method then getting the total price of all items.
private int GetTotalValue(int stat){
int total = 0;
foreach(Item i in Vendor.items){
totalStat += i.stat;
}
return total;
}
However, it has no way of knowing the name of the variable that I passed as the parameter, and thus no way of accessing it in other objects.
How would I tell the method what variable I'm passing, instead of just the value of it?
If you always want the sum of some property value you could encapsulate that logic into a method, e.g. GetVendorItemSum:
internal class Program
{
private static void Main(string[] args)
{
var items = new[] {
new Item {Price = 1},
new Item {Price = 2}
};
var vendor = new Vendor {Items = items};
var vendorSum = GetVendorItemsSum(vendor, x => x.Price);
}
private static int GetVendorItemsSum(Vendor vendor, Func<Item, int> func)
{
return vendor.Items.Sum(func);
}
}
public class Vendor
{
public IEnumerable<Item> Items;
}
public class Item
{
public int Price { get; set; }
}

How to Create and Bind the Grid for Display With Quintuple Nested Lists C# ASP.net .aspx

I'm working on a project where it is necessary for me to create and bind the grid to display a response from a server which is a list of classes and some fields, the lists of classes also contain some variables as well as another list of a different class which contains some fields and another list of a different class...and goes on for five levels.
I must display the top level class and all of the lists of classes as well as each of the nested lists within the list and by itself. Allow me to use pseudocode to try to better explain with a triple tier. I am dealing with a quintuple tier.
classA
{
List<classB> classBList;
List<classC> classCList;
int whatever;
string something;
}
ClassB
{
List<classC> classCList;
int somethingElse;
string otherThing;
}
classC
{
int somethingA;
string somethingB;
}
List<ClassA> list1;
I am trying to create and bind and display the grid for list1. I've mainly been a straight back end coder so the .aspx page is what is really throwing me for a loop. I've figured out how bind and display with fields and fields within classes and a single list, but these lists are really challenging for me and I haven't made any progress in a couple of days.
Any help is much appreciated!
Maybe something like where you flatten all the values down and use a dictionary to track their origin (if it's needed). You would then have a flattened list of all values, and could easily create or recreate an original list of values (those belonging to ClassA.ClassBList, for example) using Linq or the Dictionary keys themselves:
public class flattenedList
{
public string whatever;
public int whateverInt;
}
public class nested
{
private Dictionary<string, List<flattenedList>> listData = new Dictionary<string, List<flattenedList>>();
private List<ClassA> list1 = new List<ClassA>();
ClassA classA = new ClassA();
ClassB classB = new ClassB();
ClassC classC = new ClassC();
public void processCalsses()
{
string key = "";
foreach (ClassA a in list1)
{
key = "ClassA.ClassBList";
foreach (ClassB b in classA.classBList)
{
addToDictionary(key, new flattenedList() { whatever = b.otherThing, whateverInt = b.somethingElse });
}
key = "ClassA.ClassCList";
foreach (ClassC c in classA.classCList)
{
addToDictionary(key, new flattenedList() { whatever = c.somethingB, whateverInt = c.somethingA });
}
addToDictionary("ClassA", new flattenedList() { whatever = a.something, whateverInt = a.whatever });
}
key = "ClassB.ClassCList";
foreach (ClassC c in classB.classCList)
{
addToDictionary(key, new flattenedList() { whatever = c.somethingB, whateverInt = c.somethingA });
}
addToDictionary("ClassB", new flattenedList() { whatever = classB.otherThing, whateverInt = classB.somethingElse });
addToDictionary("ClassC", new flattenedList() { whatever = classC.somethingB, whateverInt = classC.somethingA });
foreach (KeyValuePair<string, List<flattenedList>> kvp in listData)
{
for (int i = 0; i < kvp.Value.Count; i++)
{
Console.WriteLine(key + "[" + i.ToString() + "] whatever = " + kvp.Value[i].whatever);
Console.WriteLine(key + "[" + i.ToString() + "] whateverInt = " + kvp.Value[i].whateverInt.ToString() + "\n");
}
}
}
private void addToDictionary(string key, flattenedList f)
{
if (!listData.ContainsKey(key))
{
listData.Add(key, new List<flattenedList>());
}
listData[key].Add(f);
}
public class ClassA
{
public List<ClassB> classBList = new List<ClassB>();
public List<ClassC> classCList;
public int whatever;
public string something;
}
public class ClassB
{
public List<ClassC> classCList;
public int somethingElse;
public string otherThing;
}
public class ClassC
{
public int somethingA;
public string somethingB;
}
}
Note that I had to instantiate the classes in order to get the intellisense to let me type. I assume you'd create instance versions visible to this method either within class scope or within a public static class.
PS - if you don't need to maintain the origin of each datum (which class and list it came from), then there's an easier way to do this.

How to maintain instance number in list of objects

I have a class baseClass, and a list of objects of the baseClass. What i want to achieve is that i have to dynamically assign the instance number to each object in the list. for that what am doing is that use a constructor to do this.
Following is the class definition:
public class baseClass
{
private int _InstanceNumber;
private int _MyIntVal;
private string _MyString;
public string MyString
{
get { return _MyString; }
set { _MyString = value; }
}
public int MyIntVal
{
get { return _MyIntVal; }
set { _MyIntVal = value; }
}
public int MyProperty
{
get { return _InstanceNumber; }
}
public baseClass(int instance)
{
_InstanceNumber = instance;
}
}
The creation of the List of objects is as follows:
int instanceNumber = 0;
List<baseClass> classList = new List<baseClass>();
classList.Add(new baseClass(instanceNumber++) { MyString = "sample1", MyIntVal = 10 });
classList.Add(new baseClass(instanceNumber++) { MyString = "sample2", MyIntVal = 11 });
I know it is not the actual way for creating this. it does not give the index number actually. how can i calculate the instance number?
Consider the following scenario, that am creating another list of objects then it hard to maintain the instance number. or if i create another object(this also be an instance) external to the list.
int instanceNumber = 0;
List<baseClass> anotherClassList = new List<baseClass>();
classList.Add(new baseClass(instanceNumber++) { MyString = "sample1", MyIntVal = 10 });
classList.Add(new baseClass(instanceNumber++) { MyString = "sample2", MyIntVal = 11 });
Updates:
This is my temporary solution for this. i need proper way/ method to maintain instance number
If you want to find the index of item in the list, you should ask it from the list, not the item like:
var index = list.IndexOf(item);
But it seems that you expect the item to be aware of its position in the list. In order to do this, you should pass the list to the item so it can use it to find its own place in it:
public class Item
{
private List<Item> _containerList;
public Item(List<Item> containerList)
{
_containerList = containerList;
}
public int InstanceNumber
{
get { return _containerList.IndexOf(this); }
}
}
and change your code to:
List<Item> classList = new List<Item>();
classList.Add(new Item(classList ) { ... });
classList.Add(new Item(classList ) { ... });

Get access to my derived class members

I have several classes that inhabit from this class:
public abstract class Class1
{
private string _protocol;
private static List<Plus> _class1Objects;
public string Protocol
{
get { return _protocol; }
set { _protocol = value; }
}
public static List<Plus> Class1Objects
{
get { return _class1Objects; }
set { _class1Objects = value; }
}
}
And the derive class:
public class Class2 : Plus
{
public bool name;
public int id;
}
public Webmail(string name, int id)
{
if (Class1Objects == null)
Class1Objects = new List<class1>();
.....
Class1Objects.Add(this);
}
And after my list is full of Class1Objects:
for (int i = 0; i < Class1.Class1Objects.Count; i++)
{
if (Class1.Class1Objects[i].GetType() == typeof(Class2))
}
(Class2)Class1.Class1Objects[i].
}
}
Here after (Class2)Class1.Class1Objects[i]. i cannot see my Class2 memners
You need one additional paranthese:
((Class2)Class1.Class1Objects[i]).
At the moment it is read as the following:
(Class2)(Class1.Class1Objects[i].) //<= at the '.' it is still a class1
BUT as David said in his comment: If all are of type Class2 it should be a collection of that type and if not you should check the type, altogether with foreach:
foreach(var item in Class1.Class1Objects)
{
if(item is Class2)
((Class2)Class1.Class1Objects[i]).
}
It would be cleaner to use as:
for (int i = 0; i < Class1.Class1Objects.Count; i++)
{
var c2 = Class1.Class1Objects[i] as Class2;
if (c2!=null)
}
c2.<whatever was meant to come after the .>
}
}
You might also want to consider switching to foreach unless there's a specific reason you want to manually extract each element from the List, e.g. if you're actually storing new values back into the list.
The correct syntax would be:
((Class2)Class1.Class1Objects[i]).name;
Because in your case, when you type something like this:
(Class2)Class1.Class1Objects[i].name;
You try to access the member name of Class1.Class1Objects[i], and only after that you try to cast it to Class2.
Also, the whole loop would be much simpler if you used foreach:
using System.Linq;
foreach(Class2 c in Class1.Class1Objects.OfType<Class2>())
{
Console.WriteLine(c.name); // or whatever you need to do with it
}

How to compare two distinctly different objects with similar properties

This is all in C#, using .NET 2.0.
I have two lists of objects. They are not related objects, but they do have certain things in common that can be compared, such as a GUID-based unique identifier. These two lists need to be filtered by another list which just contains GUIDs which may or may not match up with the IDs contained in the first two lists.
I have thought about the idea of casting each object list to just object and sorting by that, but I'm not sure that I'll be able to access the ID property once it's cast, and I'm thinking that the method to sort the two lists should be somewhat dumb in knowing what the list to be sorted is.
What would be the best way to bring in each object list so that it can be sorted against the list with only the IDs?
You should make each of your different objects implement a common interface. Then create an IComparer<T> for that interface and use it in your sort.
Okay, if you have access to modify your original classes only to add the interface there, Matthew had it spot on. I went a little crazy here and defined out a full solution using 2.0 anonymous delegates. (I think I'm way addicted to 3.0 Lambda; otherwise, I probably would've written this out in foreach loops if I was using 2005 still).
Basically, create an interface with the common properties. Make yoru two classes implement the interface. Create a common list casted as the interface, cast and rip the values into the new list; remove any unmatched items.
//Program Output:
List1:
206aa77c-8259-428b-a4a0-0e005d8b016c
64f71cc9-596d-4cb8-9eb3-35da3b96f583
List2:
10382452-a7fe-4307-ae4c-41580dc69146
97f3f3f6-6e64-4109-9737-cb72280bc112
64f71cc9-596d-4cb8-9eb3-35da3b96f583
Matches:
64f71cc9-596d-4cb8-9eb3-35da3b96f583
Press any key to continue . . .
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
//test initialization
List<ClassTypeA> list1 = new List<ClassTypeA>();
List<ClassTypeB> list2 = new List<ClassTypeB>();
ClassTypeA citem = new ClassTypeA();
ClassTypeB citem2 = new ClassTypeB();
citem2.ID = citem.ID;
list1.Add(new ClassTypeA());
list1.Add(citem);
list2.Add(new ClassTypeB());
list2.Add(new ClassTypeB());
list2.Add(citem2);
//new common list.
List<ICommonTypeMakeUpYourOwnName> common_list =
new List<ICommonTypeMakeUpYourOwnName>();
//in english, give me everything in list 1
//and cast it to the interface
common_list.AddRange(
list1.ConvertAll<ICommonTypeMakeUpYourOwnName>(delegate(
ClassTypeA x) { return (ICommonTypeMakeUpYourOwnName)x; }));
//in english, give me all the items in the
//common list that don't exist in list2 and remove them.
common_list.RemoveAll(delegate(ICommonTypeMakeUpYourOwnName x)
{ return list2.Find(delegate(ClassTypeB y)
{return y.ID == x.ID;}) == null; });
//show list1
Console.WriteLine("List1:");
foreach (ClassTypeA item in list1)
{
Console.WriteLine(item.ID);
}
//show list2
Console.WriteLine("\nList2:");
foreach (ClassTypeB item in list2)
{
Console.WriteLine(item.ID);
}
//show the common items
Console.WriteLine("\nMatches:");
foreach (ICommonTypeMakeUpYourOwnName item in common_list)
{
Console.WriteLine(item.ID);
}
}
}
interface ICommonTypeMakeUpYourOwnName
{
Guid ID { get; set; }
}
class ClassTypeA : ICommonTypeMakeUpYourOwnName
{
Guid _ID;
public Guid ID {get { return _ID; } set { _ID = value;}}
int _Stuff1;
public int Stuff1 {get { return _Stuff1; } set { _Stuff1 = value;}}
string _Stuff2;
public string Stuff2 {get { return _Stuff2; } set { _Stuff2 = value;}}
public ClassTypeA()
{
this.ID = Guid.NewGuid();
}
}
class ClassTypeB : ICommonTypeMakeUpYourOwnName
{
Guid _ID;
public Guid ID {get { return _ID; } set { _ID = value;}}
int _Stuff3;
public int Stuff3 {get { return _Stuff3; } set { _Stuff3 = value;}}
string _Stuff4;
public string Stuff4 {get { return _Stuff4; } set { _Stuff4 = value;}}
public ClassTypeB()
{
this.ID = Guid.NewGuid();
}
}
}
Using only .NET 2.0 methods:
class Foo
{
public Guid Guid { get; }
}
List<Foo> GetFooSubset(List<Foo> foos, List<Guid> guids)
{
return foos.FindAll(foo => guids.Contains(foo.Guid));
}
If your classes don't implement a common interface, you'll have to implement GetFooSubset for each type individually.
I'm not sure that I fully understand what you want, but you can use linq to select out the matching items from the lists as well as sorting them. Here is a simple example where the values from one list are filtered on another and sorted.
List<int> itemList = new List<int>() { 9,6,3,4,5,2,7,8,1 };
List<int> filterList = new List<int>() { 2, 6, 9 };
IEnumerable<int> filtered = itemList.SelectMany(item => filterList.Where(filter => filter == item)).OrderBy(p => p);
I haven't had a chance to use AutoMapper yet, but from what you describe you wish to check it out. From Jimmy Bogard's post:
AutoMapper conventions
Since AutoMapper flattens, it will
look for:
Matching property names
Nested property names (Product.Name
maps to ProductName, by assuming a
PascalCase naming convention)
Methods starting with the word “Get”,
so GetTotal() maps to Total
Any existing type map already
configured
Basically, if you removed all the
“dots” and “Gets”, AutoMapper will
match property names. Right now,
AutoMapper does not fail on mismatched
types, but for some other reasons.
I am not totally sure what you want as your end results, however....
If you are comparing the properties on two different types you could project the property names and corresponding values into two dictionaries. And with that information do some sort of sorting/difference of the property values.
Guid newGuid = Guid.NewGuid();
var classA = new ClassA{Id = newGuid};
var classB = new ClassB{Id = newGuid};
PropertyInfo[] classAProperties = classA.GetType().GetProperties();
Dictionary<string, object> classAPropertyValue = classAProperties.ToDictionary(pName => pName.Name,
pValue =>
pValue.GetValue(classA, null));
PropertyInfo[] classBProperties = classB.GetType().GetProperties();
Dictionary<string, object> classBPropetyValue = classBProperties.ToDictionary(pName => pName.Name,
pValue =>
pValue.GetValue(classB, null));
internal class ClassB
{
public Guid Id { get; set; }
}
internal class ClassA
{
public Guid Id { get; set; }
}
classAPropertyValue
Count = 1
[0]: {[Id, d0093d33-a59b-4537-bde9-67db324cf7f6]}
classBPropetyValue
Count = 1
[0]: {[Id, d0093d33-a59b-4537-bde9-67db324cf7f6]}
Thist should essentially get you what you want - but you may be better of using linq
class T1
{
public T1(Guid g, string n) { Guid = g; MyName = n; }
public Guid Guid { get; set; }
public string MyName { get; set; }
}
class T2
{
public T2(Guid g, string n) { ID = g; Name = n; }
public Guid ID { get; set; }
public string Name { get; set; }
}
class Test
{
public void Run()
{
Guid G1 = Guid.NewGuid();
Guid G2 = Guid.NewGuid();
Guid G3 = Guid.NewGuid();
List<T1> t1s = new List<T1>() {
new T1(G1, "one"),
new T1(G2, "two"),
new T1(G3, "three")
};
List<Guid> filter = new List<Guid>() { G2, G3};
List<T1> filteredValues1 = t1s.FindAll(delegate(T1 item)
{
return filter.Contains(item.Guid);
});
List<T1> filteredValues2 = t1s.FindAll(o1 => filter.Contains(o1.Guid));
}
}

Categories

Resources