This question already has answers here:
Anyone know a quick way to get to custom attributes on an enum value?
(2 answers)
Closed 9 years ago.
In a WinRT .NET application (C#) I want to get the custom attributes, that are defined on an enum value. Take the following enum for example:
public enum MyEnum
{
[Display(Name="Foo")]
EnumValue1,
[Display(Name="Bar")]
EnumValue2
}
Now in "normal" .NET I know that I'm able to obtain the custom attributes of an enum value with enumValue.GetType().GetMember(enumValue.ToString()).
Unfortunately, in WinRT .NET the GetMember() method isn't available on the Type class.
Any suggestions how to go with this?
=====================================================
Thanks to Marc below, I found the answer!
The following code works to get a specific custom attribute from an enum value in .NET 4.5 WinRT:
public static class EnumHelper
{
public static T GetAttribute<T>(this Enum enumValue)
where T : Attribute
{
return enumValue
.GetType()
.GetTypeInfo()
.GetDeclaredField(enumValue.ToString())
.GetCustomAttribute<T>();
}
}
Rather than looking for members, you should perhaps look specifically for fields. If that isn't available on the Type in WinRT, add using System.Reflection; and use type.GetTypeInfo() and look on there too, as various reflection facets are moved to the type-info.
Related
This question already has answers here:
C# nameof generic type without specifying type
(3 answers)
Closed 10 days ago.
I have a class:
public class StateMachine<TTag> where TTag : Enum { ... }
Which logs using Log that accepts as first argument string tag. I use nameof with StateMachine<TTag> as an argument:
_logger.Log(nameof(StateMachine<TTag>), ...)
In my app I have instances of StateMachine<TTag>, like StateMachine<AppStateTag>, etc.
And I want my StateMachine to log like this:
StateMachine<AppStateTag> ...
But instead I get:
StateMachine ...
Do I need to get weird like this?
${nameof(StateMachine)}<{nameof(TTag)}>
Is there any simple way of doing this?
So, ok, using answers from here, I've managed to frankenstein this:
$"{nameof(StateMachine<TTag>)}<{typeof(TTag).Name}>"
If anyone can suggest a better way of doing this, it would be very much appreciated.
This question already has answers here:
Can attributes be added dynamically in C#?
(10 answers)
Closed last year.
I'm trying to make a generic method and I want to pass an attribute when call it. Is it possibile or it's possible only on declaration?
Code:
public Window()
{
//Is it possible do this?:
[CustomAttribute(typeof(Something))]
MyGenericMethod();
}
private void MyGenericMethod()
{
//do stuff...
//retrieve type from CustomAttribute
}
public class CustomAttribute : Attribute
{
public CustomAttribute(Type type)
{
}
}
The short answer is NO. An attribute is used to associate metadata, or add declarative information. So you can't call an attribute when you are invoking your method. You can read more about them here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/
I consider that you will have to review your solution for your problem and find a different approach.
I don't think it's possible but you can use generic methods.
https://learn.microsoft.com/it-it/dotnet/csharp/programming-guide/generics/generic-methods
This question already has answers here:
C# extend indexer?
(6 answers)
Closed 1 year ago.
I am intrested in creating custom indexer for char[,]. It seems to me that it is prohibited, but I am wondering if there is an oportunity. The code that could have solved the problem is:
public static class GeneratorHelpers
{
public static char int[Vector2D position] (this char[,] field)
{
return field[position.X, position.Y];
}
}
The above code does not compile.
Currently, there is no such things as extension properties, operators or indexers in the C# language. The most common pattern for this would be just to take additional parameters to an extension method.
This question already has answers here:
How do I target attributes for a record class?
(2 answers)
Closed 1 year ago.
With the new C# record types in C# 9 i'd like to know wheter it is possible (for serialization) to set the JsonPropertyAttribute from Newtonsoft.Json on the constructor parameter.
It doesn't seem to work out of the box.
MWE:
using System;
using Newtonsoft.Json;
Console.WriteLine(JsonConvert.SerializeObject(new Something("something")));
record Something([JsonProperty("hello")] string world) {}
Output:
{"world":"something"}
Expected output:
{"hello":"something"}
is there an easy way to make it work like this? or do we have to revert back to the property style with a real constructor?
internal record Something
{
public Something(string world) { World = world; }
[JsonProperty("hello")] public string World { get; }
}
Per the docs:
Attributes can be applied to the synthesized auto-property and its backing field by using property: or field: targets for attributes syntactically applied to the corresponding record parameter.
So you want
record Something([property:JsonProperty("hello")] string world) {}
Without the property: qualifier, the attribute ends up on the parameter of the generated constructor (which is useful in other scenarios, like nullability).
This question already has answers here:
Create Generic method constraining T to an Enum
(22 answers)
Closed 9 years ago.
I have a generic class Foo<T> where I want to constrain T to be an enum type. Is this possible in C#?
I have tried
public class Foo<T> where T : enum // COMPILATION ERROR
but this approach only seem to work for class and struct.
Likewise, attempting to constrain T to an underlying enum type will also not work:
public class Foo<T> where T : int // COMPILATION ERROR
since int is not a class or interface.
EDIT I realize now that similar questions have been posted before, and eventually this question can be removed. One question that is even more related to my question, and that also contains the same answer as below, is this.
UPDATE SEP 13, 2018 In the latest minor C# version, 7.3, it is now possible to constrain the generic type to an Enum. For more details, see here.
That isn't valid in the C# spec and implementation, but it is in IL.
Jon Skeet made a library to get around this called Unconstrained Melody:
https://code.google.com/p/unconstrained-melody/
Though I've never used it so I cannot offer any insight into how to take advantage of this.