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

Reading attributes with reflection in C Sharp (C#) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to get the type of the class using reflection.

C Sharp (C#)
Type type = typeof([1]);
Drag options to blanks, or click blank then click option'
AAttribute
BMyClass
CGetType
DReflection
Attempts:
3 left
💡 Hint
Common Mistakes
Using GetType() instead of typeof for a type.
Using attribute or reflection keywords incorrectly.
2fill in blank
medium

Complete the code to get the custom attributes of the class.

C Sharp (C#)
object[] attrs = type.GetCustomAttributes([1], false);
Drag options to blanks, or click blank then click option'
Anull
Bfalse
Ctrue
Dtypeof(MyAttribute)
Attempts:
3 left
💡 Hint
Common Mistakes
Passing true or false instead of a Type object.
Passing null which returns all attributes.
3fill in blank
hard

Fix the error in the code to check if the attribute exists on the class.

C Sharp (C#)
bool hasAttr = type.IsDefined([1], false);
Drag options to blanks, or click blank then click option'
Atypeof(MyAttribute)
Btrue
CMyAttribute
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Passing true or false instead of a Type.
Passing the attribute class name without typeof.
4fill in blank
hard

Fill both blanks to get the first custom attribute and cast it to the correct type.

C Sharp (C#)
MyAttribute attr = (MyAttribute)type.GetCustomAttributes([1], false)[[2]];
Drag options to blanks, or click blank then click option'
Atypeof(MyAttribute)
B0
C1
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong index like 1 which may cause errors if only one attribute exists.
Passing false instead of typeof for the attribute type.
5fill in blank
hard

Fill all three blanks to read a property value from the attribute instance.

C Sharp (C#)
var value = attr.[1]; // Access property
if (value [2] [3])
{
    Console.WriteLine("Property value is valid.");
}
Drag options to blanks, or click blank then click option'
AName
B==
C"Test"
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using != instead of == causing logic errors.
Using wrong property name that does not exist.