Generics method using interface in c#
Implement an Interface with Generic Methods
namespace Win.Data
{
// Created Interface for field of table public interface IFieldTable { string Id { get; set; } DateTime TimeStamp { get; set; } string User { get; set; } string View { get; set; } string Name { get; set; } //string QData { get; set; } }
// FieldString class inhirated from IFieldTable public class FieldString : IFieldTable { public string Id { get; set; } public DateTime TimeStamp { get; set; } public string User { get; set; } public string View { get; set; } public string Name { get; set; } public string Data { get; set; } }
// FieldInt class inhirated from IFieldTable public class FieldInt : IFieldTable { public string Id { get; set; } public DateTime TimeStamp { get; set; } public string User { get; set; } public string View { get; set; } public string Name { get; set; } public int Data { get; set; } }
// FieldBool class not inhirated from IFieldTable public class FieldBool { public string Id { get; set; } public DateTime TimeStamp { get; set; } public string User { get; set; } public string View { get; set; } public string Name { get; set; } public bool Data { get; set; } } public class MyClass {
// Implemented generic method for IFieldTable interface
// new() it use here for create new object for type T
// This Method return IList Type of T where T is class implemented
// from IFieldTable Interface
public static IList<T> GetFieldData<T>() where T : IFieldTable, new() { IList<T> lst = new List<T>(); T t = new T(); t.User = "Harshal Patel"; t.Name = "Field_Name"; t.View = "Form_Name"; t.TimeStamp = DateTime.Now; switch (t.GetType().Name) { case "FieldInt": (t as FieldInt).Data = 0; break; case "FieldString": (t as FieldString).Data = "Data"; break; default: break; } lst.Add(t); return lst; }
} }
Now you will be call this generic method from your code like below.// Here method call for FieldString classvar lstString = MyClass.GetFieldData<FieldString>();// Here method call for FieldInt classvar lstInt = MyClass.GetFieldData<FieldInt>();// Here will get the compile time error,//Because of FieldBool class not inherited from IFieldTable interfacevar lstBool = MyClass.GetFieldData<FieldBool>();
Comments
Post a Comment