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

Custom attribute classes 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 declare a custom attribute class named MyAttribute.

C Sharp (C#)
public class [1] : System.Attribute {}
Drag options to blanks, or click blank then click option'
AMyAttribute
BCustomAttr
CAttributeClass
DMyClass
Attempts:
3 left
💡 Hint
Common Mistakes
Naming the class without 'Attribute' suffix.
Not inheriting from System.Attribute.
2fill in blank
medium

Complete the code to apply the custom attribute MyAttribute to the class Sample.

C Sharp (C#)
[[1]]
public class Sample {}
Drag options to blanks, or click blank then click option'
AMyClass
BAttribute
CCustomAttribute
DMyAttribute
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong attribute name.
Missing the square brackets.
3fill in blank
hard

Fix the error in the attribute constructor to accept a string parameter named description.

C Sharp (C#)
public class MyAttribute : System.Attribute {
    public string Description { get; }
    public MyAttribute([1]) {
        Description = description;
    }
}
Drag options to blanks, or click blank then click option'
Adouble description
Bint description
Cstring description
Dbool description
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong parameter type.
Mismatching parameter name and property.
4fill in blank
hard

Fill both blanks to create a dictionary using ToDictionary that maps property names to their types for properties with type string.

C Sharp (C#)
var stringProps = typeof(MyAttribute).GetProperties()
    .Where(prop => prop.PropertyType == typeof(string))
    .ToDictionary(prop => [1], prop => [2]);
Drag options to blanks, or click blank then click option'
Aprop.Name
Bprop.PropertyType
Cprop.GetValue(this)
Dprop.ToString()
Attempts:
3 left
💡 Hint
Common Mistakes
Using property values instead of names or types.
Using incorrect property methods.
5fill in blank
hard

Fill all three blanks to create a method that returns the description from the MyAttribute applied to a class.

C Sharp (C#)
public static string GetDescription(Type t) {
    var attr = (MyAttribute)Attribute.GetCustomAttribute(t, typeof([1]));
    return attr == null ? [2] : attr.[3];
}
Drag options to blanks, or click blank then click option'
AMyAttribute
Bstring.Empty
CDescription
DAttribute
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong attribute type in GetCustomAttribute.
Returning null instead of empty string.
Accessing wrong property name.