How to pass one class as a parameter of another class
Pass C# class as a parameter of another class
In this article we will learn to pass one class as a parameter
of another class. In broad sense ,we are trying to create parameterized class
where we will pass another class as parameter and we will use the property of the
parameter class.
This article demands little knowledge of parameterized
class. If you are completely new in this concept then below paragraph is for
quick understanding of same.
What is parameterized class?
In case of function we use and pass parameter to pass value.
In C# we can pass parameter to a class and the class which takes parameter is
called parameterized class or generic class. Try to understand below code.
class TestClass<T>
{
//Create object of parameterized class.
T obj;
}
This is small example of parameterized class and in place of T we
can pass any object, event it may be another class. In below example we will try
to implement one complete example of parameterized class. Have a look on below
code.

In this above example we created two classes. The Second class is
our main class which we are passing as a parameter of First class. Here is code of Main() function.
Second s = new Second();
s.name = "sourav";
s.surname = "kayal";
First<Second> objf = new First<Second>();
At first we are creating object of “Second” class and then setting
values to properties, after that we are creating object of “First” class by
passing “Second” class as object.
But the problem is that we are not able to access the property of
Second class within first class. In above example After T( Type) we are giving “.”
But IDE is not showing any property. If we want to use property of parameter class
then we have to use “where” keyword. Try to understand below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApp
{
class First<T> where T:Second
{
public First(T tmp)
{
Console.WriteLine("Name is : " + tmp.name);
Console.WriteLine("Surname is : " + tmp.surname);
}
}
class Second
{
public string name { get; set; }
public string surname { get; set; }
}
class Program
{
static void Main(string[] args)
{
Second s = new Second();
s.name = "sourav";
s.surname = "kayal";
First<Second> objf = new First<Second>(s);
Console.ReadLine();
}
}
}
Here is sample output.
Conclusion:-
In this quick article we have learned how to pass class as a
parameter of another class. Hope you have learned the concept.