Click here to Skip to main content
15,847,077 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I am just trying to explore Generic class in C#.
I am trying to pass an object to the class Test and I am assigning the _value the customer object.

How to retrieve the customer object value in write method below?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1

    public class Customer

        public int CusomerId { get; set; }
        public string CustomerName { get; set; }
        public int CustomerAge { get; set; }

    public class Test<T>

        T _value;

        public Test(T t)

            _value = t;

//i am trying here to get the customer object from _value which i assigned in _value
//i cant even use foreach in generic class...
        public void write()



    class Program
        static void Main(string[] args)
            Customer obj = new Customer();
            obj.CusomerId = 1001;
            obj.CustomerAge = 23;
            obj.CustomerName = "Anurag";

            Test<object> T1 = new Test<object>(obj);
Kindly help me
Updated 21-Feb-14 8:40am

Try this:
public class Test<T> where T : Customer

where T : Customer makes sure you can only use the type Customer or types derived from Customer.

Then, change this line in the Main method:
Test<Customer> T1 = new Test<Customer>(obj);

Change object into Customer, otherwise you will get a compiler error.

Now, you will be able to access the properties from the Customer class from your generic class.
Share this answer
anurag19289 21-Feb-14 14:05pm    
I am getting error--> constraints are not allowed on non-generic declarations
Thomas Daniels 21-Feb-14 14:09pm    
On what line do you get this error?
anurag19289 21-Feb-14 14:07pm    
i think as i m using visual studio 2008 probably it doesnot support...
anurag19289 21-Feb-14 14:08pm    
so is it the only way to do so ?
anurag19289 21-Feb-14 14:10pm    
in this line itself i am getting error

public class Customer where T : Customer
try this in your write() method
object a = _value;
Customer c = (Customer)a;
Share this answer
anurag19289 21-Feb-14 21:11pm    
cool... :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900