0
0
C Sharp (C#)programming~20 mins

Default keyword for generic types in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Default Keyword with Generic Types in C#
📖 Scenario: Imagine you are creating a simple program that works with different types of data. Sometimes, you need to set a variable to its default value without knowing its exact type in advance.
🎯 Goal: You will build a small C# program that uses the default keyword with generic types to assign default values to variables of different types.
📋 What You'll Learn
Create a generic method that returns the default value of its type parameter.
Call this method with different types like int, string, and a custom class.
Print the default values to the console.
💡 Why This Matters
🌍 Real World
Using the <code>default</code> keyword with generics helps write flexible code that works with many types without knowing them in advance.
💼 Career
Understanding generics and default values is important for writing reusable and safe code in C# software development.
Progress0 / 4 steps
1
Create a generic method to return default value
Write a generic method called GetDefaultValue with a type parameter T that returns default(T).
C Sharp (C#)
Need a hint?

Use default(T) inside the method to get the default value of the generic type.

2
Call the generic method with different types
Inside the Main method, create three variables: intDefault assigned to GetDefaultValue<int>(), stringDefault assigned to GetDefaultValue<string>(), and customDefault assigned to GetDefaultValue<MyClass>(). Also, define an empty class called MyClass outside Program.
C Sharp (C#)
Need a hint?

Call GetDefaultValue with the type inside angle brackets <> and assign the result to variables.

3
Print the default values to the console
Add Console.WriteLine statements inside Main to print intDefault, stringDefault, and customDefault. Use ?? "null" to show "null" for reference types.
C Sharp (C#)
Need a hint?

Use ?? "null" to print "null" if the value is null.

4
Run the program and see the output
Run the program to see the printed default values for int, string, and MyClass.
C Sharp (C#)
Need a hint?

The default value for int is 0, and for reference types like string and MyClass it is null.