Friday, August 30, 2013

C# Coding help

I am a novice when it comes to programming, but do have a slight understanding of how. I read a lot of C# books and patterns books, and I am stumped on how to perform something. So basically what I am trying to do, is I have a base class which has all properties and methods that I need. I then will have 1 to n child classes that will inherit the base class, these child classes will only contain some new properties, and will override a method in the base class.


I am not sure if I am going about it the wrong way or not, like I said I am a novice, but I am not sure what class will need to be created, so based on some patterns I created a factory class, that creates the proper class based on users choice. When I instantiate the classes I to them as the base class, and because I do this, I cannot access the properties in the child classes, and I am curious on how to go about doing it properly. Below is a code example, to give an understanding of what I mean, as I am obviously going about it the wrong way, or I am just missing something, but any help is greatly appreciated, in my learning experience.



namespace Test
{
public enum ClassTypes
{
ChildClass,
Default
}

public class BaseClass
{
public Int64 Id { get; set; }
public string Details { get; set; }

// Child classes will override this method
public virtual void Save()
{
Console.WriteLine("Saving.....");
Console.WriteLine("Id: {0} - Details: {1}", this.Id, this.Details);
}
}

public class ChildClass : BaseClass
{
public string ExtraDetails { get; set; }

public override void Save()
{
// Call base's save method
base.Save();
Console.WriteLine("Extra Details: {0}", this.ExtraDetails);
}
}

// Factory Class to instansiate proper class
public static class ClassFactory
{
public static BaseClass CreateClass(ClassTypes classType)
{
switch (classType)
{
case ClassType.ChildClass:
return new ChildClass();
default:
return new BaseClass();
}
}
}

class Program
{
static void Main(string[] args)
{
BaseClass bc1 = ClassFactory.CreateClass(ClassTypes.Default);
BaseClass bc2 = ClassFactory.CreateClass(ClassTypes.ChildClass);

IList<BaseClass> list = new List<BaseClass>();

bc1.Id = 1;
bc.Details = "Testing Base Class";
list.Add(bc1);

bc2.Id = 2;
bc2.Details = "Testing child class";
// Can NOT access because type being BaseClass
bc2.ExtraDetails = "Extended testing";
list.Add(bc2);

foreach (BaseClass bc list)
{
bc.Save();
}

Console.ReadLine();
}
}
}





If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.



Don't Retire Technet


No comments:

Post a Comment