Files
freeCodeCamp/guide/english/csharp
Willy David Jr a9fb8ac1c3 Corrected access on constant variable and access on attribute properties. (#36586)
First on constant variable issue:

This will not compile:

[Plugin(MyPluginName)] // Won't compile because MyPluginName isn't const
[Plugin(MyConstPluginName)] // OK
[Plugin("My Cool Plugin")] // OK

In order to access properties on the static class, it must specify the name of the class before the properties name as proposed on this change:

[Plugin(Variables.MyPluginName)] // Won't compile because MyPluginName isn't const
[Plugin(Variables.MyConstPluginName)] // OK
[Plugin("My Cool Plugin")] // OK

Second on access on attribute properties:

In order to access plugin.Name on this code:

var type = typeof(MyPlugin); // Returns a Type object representing our MyPlugin class
	var attributes = System.Attribute.GetCustomAttributes(type); // Returns an Attribute[]

	foreach (var a in attributes)
	{
		if (a is PluginAttribute plugin)
			Console.WriteLine($"Plugin Name: {plugin.Name}");
	}

You need to cast if first to the right class, then access the properties, as the above code will generate a compile-time error:

var type = typeof(PluginAttribute); // Returns a Type object representing our PluginAttribute class
	var attributes = System.Attribute.GetCustomAttributes(type); // Returns an Attribute[]

	foreach (var a in attributes)
	{
		if (a is PluginAttribute)
                    {
                        PluginAttribute plug = (PluginAttribute)a; //Cast it first to PluginAttribute class before you can access all accessible properties
                        Console.WriteLine($"Plugin Name: {plug.Name}");
                    }
	}
2019-08-20 09:32:05 -07:00
..
2019-07-19 23:48:04 -05:00
2019-05-17 08:02:17 -07:00
2019-07-10 18:08:28 -07:00