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
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:
Cast List<T> to List<Interface>
(10 answers)
Closed 3 years ago.
I have a class which implements an interface. A second class implements an IList<> of this first class. I need to assign this second class to a generic property which is an IList<> of the interface.
This is a demo for the code I use:
public class SODemo
{
public SODemo()
{
ClassWithIListOfClassWithInterface classWithIList = new ClassWithIListOfClassWithInterface();
IList<IDemoInterface> listOfInterfaces;
// CS0266: Cannot implicitly convert type ...
listOfInterfaces = classWithIList;
}
}
public class ClassWithInterface : IDemoInterface
{
// ...
}
public class ClassWithIListOfClassWithInterface : IList<ClassWithInterface>
{
// ...
}
From answers on similar problems I found out that it seems not work at all.
Why do I need this?
I have a lot of classes which are implemented like ClassWithIListOfClassWithInterface and I need a generic handler for them.
Question:
My goal is to access each element in listOfInterfaces through the methods implemented in the interface.
Is there any alternative I can use?
Edit
I already tried this
listOfInterfaces = (IList<IDemoInterface>)classWithIList;
but then I get an System.InvalidCastException at runtime.
The problem is not with your class itself, but rather with the conversion between IList<IDemoInterface> and IList<ClassWithInterface>.
IList<T> in C# are said to be "invariant in T". This means that you cannot make conversions between IList<T1> and IList<T2> directly, even if they have an inheritance relationship.
What you can do is to create an IList<IDemoInterface> and copy every element from your source IList<ClassWithInterface> to it. Of course that'd be rather cumbersome, so the LINQ way of doing it is that:
listOfInterfaces = classWithIList.Cast<IDemoInterface>().ToList();
This question already has answers here:
What is the difference between a field and a property?
(33 answers)
Closed 8 years ago.
Suppose I have a property in a class as in the following:
class testclass
{
public string Name {get; set;}
public void dosomething(){//...}
}
There is no functional difference between this format and the following:
class testclass
{
public string name;
public void dosomething(){//...}
}
Both name fields can be set to anything including an empty string and both can retrieve just without any restrictions. So what is the use of the property semantics detailed above where there is no validation or other process in the get and set methods? One use I see is that you can remove either the get or set method to make it write only or read only, respectively. I don't know what other use this would serve.
The main reason is so that you can change the implementation later without breaking client code. You might not do any validation or raise an event now but what if you decide to in the future? Also, properties can be bound while fields can't.
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.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do you give a C# Auto-Property a default value?
Hi all:
If I want to add default value, says 60, to following property for a class, what is the most convenient way in C#3.0
public int someSetting { get; set; }
You need to initialize it in all constructors.
Put it in the parameterless constructor, that's what I'd do.
Edit: Yes, I guess what I mean by the above is any constructor where the parameter in question is not passed in.
I would think the best way is to set the default in the constructor of the class