Generic and Generic Constant in C#
Generic and Generic Constant in C#
Constant in C#
Group 6: (Noor Fatima, Uswa Asif, Kiran Farooq)
Generic and Generic
Constant, Purposes
(Noor Fatima | 23179 | ADP (CS) MA )
Generic
A generic is like a blueprint that can work with any type of
data.
Explaination
Instead of making separate code for each type (like for
int, float, or string), you write one generic code that
works for all types.
It helps to make the code reusable, flexible, and safe.
Example
Example in simple words: Imagine you have one box,
and you can put anything in it — a book, a toy, or clothes.
Similarly, in programming, a generic can hold or work
with any data type.
Generic constant
A generic constant is a fixed value used inside a
generic.
It doesn't change, and it can be used across different
types while keeping the value same.
It helps to make generics more powerful by adding fixed
values that apply for all types.
Example
Example in simple words: Think of a pizza recipe that
always needs 2 cups of flour — no matter if you are
making small, medium, or large pizza sizes.
Here, 2 cups of flour is like a generic constant — it
stays the same across different cases.
Summary:
Generic = flexible code for any type.
Generic Constant = fixed value used inside a generic
code.
Purpose
To define a fixed, unchangeable value that works for
any data type.
To ensure consistency and readability in generic code.
To avoid magic numbers or hardcoded values when
working with generics.
Understanding Generic
Classes, Methods, and
Constants
(Uswa Asif | 23178 | ADP (CS) MA )
Generic Class in C#
• Defines a type parameter in the class declaration.
• Operates on any data type without losing type
safety.
Example:
class Box<T>
{
private T value;
Example:
class Test<T>
{
public const T DefaultValue = default(T); // Error!
}
class Test<T>
{
public static readonly T DefaultValue = default(T);
}
default(T) provides:
• 0 for numbers,
• false for bool,
• null for reference types.
Advantages and
Conclusion
(Kiran Farooq | 23177 | ADP (CS) MA )
Advantages/Benefits of Generic in C#
• Type Safety: Ensures you're using the correct data type.
• Reusability: Write code once, use it with many types (e.g., int, string, custom classes).
• No Casting: No need to cast objects, reducing errors.
• Better Performance: Avoids boxing/unboxing overhead.
• Code Readability: Clearly communicates the type being used.
Conclusion of Generic in C#
Generics help you write flexible and reusable code that works with any data type. They
provide type safety, reducing errors and improving performance.
Generic VS Constant
You can't use constants (const) directly in generics because the type is unknown until runtime.
Instead, use readonly fields or default(T) to achieve similar results.