I've read the answers for Class with indexer and property named "Item", but they do not explain why can I have a class with multiple indexers, all of them creating Item property and get_Item/set_Item methods (of course working well, as they are different overloads), but I cannot have an explicit Item property.
Consider the code:
namespace Test
{
class Program
{
static void Main(string[] args)
{
}
public int this[string val]
{
get
{
return 0;
}
set
{
}
}
public string this[int val] //this is valid
{
get
{
return string.Empty;
}
set
{
}
}
public int Item { get; set; } //this is not valid
}
}
For two indexers there are four methods created:
Int32 get_Item(String val)
Void set_Item(String val, Int32 value)
String get_Item(Int32 val)
Void set_Item(Int32 val, String value)
I'd expect my property to create
Int32 get_Item()
Void set_Item(Int32 value)
These overloads are generally acceptable, but somehow the compiler won't let me create such a property.
Please note that I don't need a way to rename the indexer etc, this is known - I need an explanation. This answer: https://stackoverflow.com/a/5110449/882200 doesn't explain why I can have multiple indexers.
For the same reason that the following won't compile:
public class Test
{
public int Foo
{
get;
set;
}
public void Foo()
{
return;
}
}
The above results in "The type 'Test' already contains a definition for 'Foo'". Although these could be implemented as a Foo() method and a get_Foo() method, the naming is an implementation detail - at the language level, it's .Foo() and .Foo and since not all languages would support that, the compiler considers it an error.
Similarly, other languages may not support having an indexer and a property with the same name. So, although as you point out this could be compiled as get_Item() and get_Item(Int32), the CLR designers nevertheless chose not to allow it. Although the CLR could have been designed to allow this, it may not be supported at the language level, so they chose to avoid any such issues.
Related
in my C# class, I want to refer to type of the class itself, is it possible?
my sample code:
in the line of
private static List<CRcpParmPropEle<CParam1, string>> ParmPropList;
I don't want to use "CParam1", I wish to use some general way (like "this") to refer to itself. because I have many classes like CParam1, everyone would need to refer to itself this way.
class CParam1
{
private double m_Prop1;
private static List<CRcpParmPropEle<CParam1, string>> ParmPropList;
public CParam1()
{
}
////-> I wish to replace Cparam1 to something like this
public static List<CRcpParmPropEle<CParam1, string>> getParmPropList()
{
if (ParmPropList == null)
{
ParmPropList.Add(new CRcpParmPropEle<CParam1, string>("Prop1", "BA", 0, false));
//-> I wish to replace Cparam1 to something like this
}
return ParmPropList;
}
public string Prop1
{
get
{
return m_Prop1.ToString();
}
set
{
m_Prop1 = -1;
double dW1;
if (double.TryParse(value, out dW1))
{
m_Prop1 = dW1;
}
}
}
public class CRcpParmPropEle<T,TProp>
{
public Func<T, TProp> getter;
public Action<T, TProp> setter;
public string PropName { get; set; }
public string ColPos { get; set; }
public int ColNum { get; set; }
public int RowNum { get; set; }
public bool ReadOnly { get; set; }
public CRcpParmPropEle(string strPropName, string strColPos, int nRowNum, bool bReadOnly)
{
PropName = strPropName;
ColPos = strColPos;
RowNum = nRowNum;
ReadOnly = bReadOnly;
var prop = typeof(T).GetProperty(PropName); //typeof(rcpObj).GetProperty(propName);
getter = (Func<T,TProp>)Delegate.CreateDelegate(typeof(Func<T,TProp>), prop.GetGetMethod());
setter = (Action<T,TProp>)Delegate.CreateDelegate(typeof(Action<T,TProp>), prop.GetSetMethod());
}
}
In general, no. There is no way to do this. Since in the contexts where this would typically be used, one is writing code specific to the type anyway, and since we are used to having to specify the type name for static members anyway, this doesn't seem like much of a hardship.
But, there are a couple of alternatives that could work in your scenario, both involving generics.
The first is to delegate the construction of the new object to a generic helper method:
public static List<CRcpParmPropEle<CParam1, string>> getParmPropList()
{
if (ParmPropList == null)
{
AddToList(ParmPropList, "Prop1", "BA", 0, false);
}
return ParmPropList;
}
private static void AddToList<T>(List<CRcpParmPropEle<T, string>> list, string s1, string s2, int i, bool f)
{
list.Add(new CRcpParmPropEle<T, string>(s1, s2, i, f));
}
In this way, the actual type is inferred from the type of the List<T> object being passed in, and so doesn't need to be restated. Of course, you don't get out of specifying the type somewhere. It just doesn't wind up at this particular call site.
Another option is to use a static helper class to implement the static functionality of your CParam1 class:
static class ParmPropClass<T>
{
private static List<CRcpParmPropEle<T, string>> ParmPropList;
public static List<CRcpParmPropEle<T, string>> getParmPropList()
{
if (ParmPropList == null)
{
ParmPropList.Add(new CRcpParmPropEle<T, string>("Prop1", "BA", 0, false));
}
return ParmPropList;
}
}
Then when you use the static members, you have to specify the type name as ParmPropClass<CParam1> (or whatever, depending on what you wind up naming the helper class). Again, you don't get out of specifying the type name somewhere, but the call site doesn't need to.
In fact, if you are doing this kind of pattern exactly in a number of locations, the generic helper type might be a better way to go, since then you don't have to copy/paste code all the time (a recipe for failing to fix some bug in all the places it was copied to).
There is no straight forward or easy to implement answer here. I'll give you three options but I don't think any of these would be easier than just changing all of the classes. If I had to do this right I would use a dependency injector. in the long run you will be better off and you'll be able to handle this stuff easier next time around. If I had to do it fast and desperate I would use reflection.
Option 1 - Reflection
You could assemble the List at runtime using reflection.
Look at this post for an example of creating a list at runtime with reflection.
Generic list by using reflection
This will make your code really nasty to maintain and you will have to use reflection throughout to manage the list. You would probably add more headaches in runtime errors and difficulty debugging than just changing it everywhere
Option 2 - Common Base Class
If you can make all the CPARAM1 type objects implement from a common base class CPARAMBASE you could define the list using the common base class.
private static List<CRcpParmPropEle<CParamBase, string>> ParmPropList;
Option 3 - Dependency Injection
This isn't something you can just cover in a SO answer but look at dependency injection.
You create an interface between all of the CPARAM type classes and then you inject a concrete type for based on what type it is being injected into.
[Inject]
private static List<CRcpParmPropEle<ICParam, string>> ParmPropList;
In your dependency Injection you could define that ICParam instance would be.
this.Bind<List<CRcpParmPropEle<ICParam, string>>>()
.To<List<CRcpParmPropEle<CParam1, string>>>()
.WhenInjectedInto(typeof(CParam1));
Look up Ninject and then Contextual Binding and http://www.ninject.org/wiki.html
For an object sellprint declared as static in the class
private static string sellprint = "";
public string Sellprint
{
get { return sellprint; }
}
public void SetSellprint(string x)
{
sellprint = x;
}
How is this
different from
public string Sellprint
{
get; set;
}
internally.
I could not find any examples of code 1 on msdn. what does it translate into?
The compiler creates a getter method for your property in the first code that returns the value of sellprint field because you implement only the getter method.In the second code, both getter and setter methods creating by compiler and also the backing-field.That's the difference.
You can verify that using ILDASM.exe:
First, consider this code:
class Foo
{
private string _value;
public string Value
{
get { return _value; }
}
public void SetValue(string str)
{
_value = str;
}
}
As you can see there is only one method generated by compiler which is get_Value.
If we change it like this and make the Value an auto-implemented property:
class Foo
{
public string Value { get; set; }
}
You can see that compiler creates both getter (get_Value) and setter (set_Value) method and also create a private backing field for the property.
There is no pros or cons about the functionality except in the second code you are doing the same work with less code.
1) should not work because there is no sellprint - assuming you have a field named sellprint and just forgot in your code snippet, you provide a get accessors and a method instead of the set accessors, which is kinda strange.
2) will create the field required automatically (and will not tell you the name, so you cannot accidentally use it)
There is not difference between those two though.
I'm looking to use "phantom types" to implement type-safe identifiers. There's a question here about doing this in F#.
I'd like to do this in C#. How?
I've got a solution (which has problems), so I'll post it as a possible answer to see if anyone can improve it.
Why not make it a sealed class with its constructor private?
public sealed class Id<TDiscriminator>
{
private Id() { }
//some static methods
}
I've come up with the following:
struct Id<TDiscriminator>
{
private readonly Guid _id;
private Id(Guid id)
{
_id = id;
}
public Guid Value
{
get { return _id; }
}
public static Id<TDiscriminator> NewId()
{
return From(Guid.NewGuid());
}
public static Id<TDiscriminator> From(Guid id)
{
return new Id<TDiscriminator>(id);
}
public static readonly Id<TDiscriminator> Empty = From(Guid.Empty);
// Equality operators ellided...
}
...which I can use as follows:
class Order { /* empty */ }
class Customer { /* empty */ }
void Foo()
{
var orderId = Id<Order>.NewId();
var customerId = Id<Customer>.NewId();
// This doesn't compile. GOOD.
bool same = (orderId == customerId);
}
I don't particularly want concrete classes for the discriminator, because I don't want anyone instantiating them.
I could get around that by using an interface or an abstract class. Unfortunately, these can still be derived from and instantiated.
C# won't let you use a static class as a type argument. I can't say that I'm totally happy with the answers to that question, because the answers basically say "just because".
How about?
public sealed class Order
{
private Order() {}
}
public static sealed class Id<T>
{
// ...
}
I think that's exactly what you say. No one (except some special cases) can construct it and no one can inherit from it.
Well, as far as I could understand, you would like to provide a mechanism for distinguishing different types by a custom identifier object. I think you are almost near a working solution. In .NET when having a generic class, each substitution of the generic argument (or each unique combination of the generic arguments, if more than one) creates a unique type in the runtime. In your code Id<Order> and Id<Customer> are two distinct types. The NewId() method returns an instance of Id<Order> for the orderId and Id<Customer> for the customerId variables. The two types do not implement the == operator and therefore cannot be compared. Moreover, such comparison would be difficult to implement, since you cannot determine all possible uses of the Id<TDsicriminator> - you cannot guess what type will the TDsicriminator be substituted with.
1
A fast and simple solution will be to do this:
class Order { /* skipped */ }
class Customer { /* skipped */ }
void Foo()
{
var orderId = Id<Order>.NewId();
var customerId = Id<Customer>.NewId();
bool sameIds = (orderId.Value == customerId.Value); // true
bool sameObjects = orderId.Equals(customerId); // false
}
Since the Value properties are both of the Guid type, comparison is possible.
2
If you need however, to implement the == operator, or some sort of equality comparisons for instances of Id<TDisciminator>, the approach will be different. What comes up to my mind is the following:
public abstract class IdBase
{
public abstract Guid Value { get; protected set; }
public static bool operator == (IdBase left, IdBase right)
{
return left.Value == right.Value;
}
}
public sealed class Id<TDiscriminator> : IdBase
{
// your implementation here, just remember the override keyword for the Value property
}
Many people would not recommend the second approach though, since different implementations of IdBase may happen to have the same Value property (if you used the constructor that passes an existing ID). For instance:
var guid = Guid.NewGuid();
var customerID = Id<Customer>.From(guid);
var orderID = Id<Order>.From(guid);
Here (customerID == orderID) will then return true which is probably not what you want.
Shortly, in such a case, two different types will count as equal, which is a big logical mistake, so I'd stick to the first approach.
If you need Id<Customer>.Value to always be different than Id<Order>.Value, because of the different generic arguments (Customer is different than Order), then the following approach will work:
public sealed class Id<in TDiscriminator>
{
private static readonly Guid _idStatic = Guid.NewGuid();
private Id()
{
}
public Guid Value
{
get { return _idStatic; }
}
}
Notice the in keyword used here. This is applicable for .NET 4.0 where generics can be covariant and ensures that your class uses contravariant generics. (see http://msdn.microsoft.com/en-us/library/dd469487.aspx). In the above code, the _idStatic field will have a unique value for every different type supplied as a generic argument.
I hope this info is helpful.
Is there an equivalent of this in C# for static members?
I like to use this to make my code more readable, but wondered if there was an equivalent for static members.
I suppose if you use this. to reinforce that you are referring to instance members, the equivalent in a static member would be to use ClassName.
But stylistically, why add code that doesn't change meaning?
edit to add various clarifications:
My last sentence above can be illustrated with these examples:
class Example1
{
public int J { get; set; }
public Example1()
{
J = 0;
}
// These two methods have *exactly* the same CIL
public int InstanceMethodLong()
{
return this.J;
}
public int InstanceMethodShort()
{
return J;
}
}
The this. in InstanceMethodLong does not change the meaning as compared with InstanceMethodShort.
Statically:
class Example2
{
public static int K { get; set; }
static Example2()
{
K = 0;
}
// These two methods have *exactly* the same CIL
public int StaticMethodLong()
{
return Example2.K;
}
public int StaticMethodShort()
{
return K;
}
The Example2. in StaticMethodLong does not change the meaning as compared with StaticMethodShort.
In both these cases, adding the qualifier results in the same CIL, the same behaviour, and is more source to write, read, and understand. Stylistically - and I will happily accept that this is a question of code style - I see no reason for it to be there.
With underscore prefixes the situation is slightly different:
class Example3
{
int _j;
public int J
{
get { return _j; }
set
{
_j = value;
// and do something else,
// to justify not using an auto-property
}
}
public Example3()
{
J = 0;
}
public int MethodWithParameter(int j)
{
// Now there is a *difference* between
return j;
// and
return _j;
}
}
Here, in MethodWithParameter, there is a difference between referring to _j and j - so we are deliberately and explicitly expressing different meaning. It's true that the compiler doesn't care what we call our variable names, but it does care what variables we are referring to! So in the body of MethodWithParameter, using or not using an underscore isn't just stylistic, it's semantic. Which isn't the particular issue we're addressing in this question.
As a static member is not meant to belong to any particular instance (as this refers to an instance of an object, with different settings possible per instance), what you would instead want to do is use ClassName.Member instead of this.Member.
public class Orange
{
public static string Tastes = "sweet";
public static string FoodType(){
return "fruit";
}
}
Would be called by:
Console.WriteLine(Orange.Tastes);
Same goes for static methods, as well:
Console.WriteLine(Orange.FoodType()).
Please note this is a contrived example for demonstration only. :)
You may able to use the class name to reference other static properties.
Your code becomes a bit more resistant to copy/paste but that's not always a bad thing.
Unfortunately no, there is no this for static methods. To help differentiate static members from class members I prefix it with the class name.
class Test {
static Regex TextRegex = new Regex(...);
public static bool TestString(string input) {
return Test.TextRegex.IsMatch(input);
}
}
I like "this" as well to realsie from the first look where the state is changing. You may want to consider type's name for static members in this case.
I have some extension methods which could be used like this:
MyType myObject;
string displayName = myObject.GetDisplayName(x => x.Property);
The problem here is that it needs an instance, even if the extension method only needs the type MyType. So if there is no instance, it needs to be called like this:
string displayName = BlahBlahUtility.GetDisplayName((MyTpe x) => x.Property);
Which is not so nice anymore.
Is there a way to write better syntax for such cases?
What I actually want to do is this (pseudo language):
string displayName = MyType.Property.GetDisplayName()
Which of course does not work with C#.
But what about something like this:
string displayName = ((MyType x) => x.Property).GetDisplayName();
This is also not possible (after a lambda, a dot is not accepted).
Any ideas?
Edit:
My "favorite syntax" MyType.Property.GetDisplayName() seems to be misleading. I don't talk about static properties here. I know that this syntax won't be possible. I just tried to show in pseudo language, what information is necessary. This would be ideal, every additional stuff is just syntactical overhead. Any working syntax that is close to this would be great.
I don't want to write a certain extension method. I want an easy, readable and compile time safe syntax, using any language feature.
Have a look at the Express and Reflect classes in the Lokad Shared Libraries. Think they may help out with what you are trying to do. Read more here:
Strongly Typed Reflection in Lokad Shared
How to Find Out Variable or Parameter Name in C#?
From your comment: "I want an easy and compile time safe syntax to get information about members".
This is a very frequently requested feature and has been discussed in the C# team's meetings for about a decade, but has never been prioritised high enough to be included.
This blog post explains why:
http://blogs.msdn.com/ericlippert/archive/2009/05/21/in-foof-we-trust-a-dialogue.aspx
So for now, you're just going to be fighting against a missing feature. Maybe you could post more information about your broader problem and see if people can suggest different approaches.
Update
Without more info about your problem this is just guesswork. But if you have a property that represents a value but also carries additional "meta" information, you could always represent that as a new type and use an "injection" step to set everything up.
Here's a suggested abstract interface to such a "meta property":
public interface IMetaProperty<TValue>
{
TValue Value { get; set; }
string DisplayName { get; }
event Action<TValue, TValue> ValueChanged;
}
The value of the property is just another sub-property, with its type defined by the user.
I've put in the display name, and also as a bonus you've got an event that fires when the value changes (so you get "observability" for free).
To have properties like this in a class, you'd declare it like this:
public class SomeClass
{
public IMetaProperty<string> FirstName { get; private set; }
public IMetaProperty<string> LastName { get; private set; }
public IMetaProperty<int> Age { get; private set; }
public SomeClass() { MetaProperty.Inject(this); }
}
Note how the setters on the properties are private. This stops anyone from accidentally setting the property itself instead of setting the Value sub-property.
So this means the class has to set up those properties so they aren't just null. It does this by calling a magic Inject method, which can work on any class:
public static class MetaProperty
{
// Make it convenient for us to fill in the meta information
private interface IMetaPropertyInit
{
string DisplayName { get; set; }
}
// Implementation of a meta-property
private class MetaPropertyImpl<TValue> : IMetaProperty<TValue>,
IMetaPropertyInit
{
private TValue _value;
public TValue Value
{
get { return _value; }
set
{
var old = _value;
_value = value;
ValueChanged(old, _value);
}
}
public string DisplayName { get; set; }
public event Action<TValue, TValue> ValueChanged = delegate { };
}
public static void Inject(object target)
{
// for each meta property...
foreach (var property in target.GetType().GetProperties()
.Where(p => p.PropertyType.IsGenericType &&
p.PropertyType.GetGenericTypeDefinition()
== typeof(IMetaProperty<>)))
{
// construct an implementation with the correct type
var impl = (IMetaPropertyInit)
typeof (MetaPropertyImpl<>).MakeGenericType(
property.PropertyType.GetGenericArguments()
).GetConstructor(Type.EmptyTypes).Invoke(null);
// initialize any meta info (could examine attributes...)
impl.DisplayName = property.Name;
// set the value
property.SetValue(target, impl, null);
}
}
}
It just uses reflection to find all the IMetaProperty slots hiding in the object, and fills them in with an implementation.
So now a user of SomeClass could say:
var sc = new SomeClass
{
FirstName = { Value = "Homer" },
LastName = { Value = "Simpson" },
Age = { Value = 38 },
};
Console.WriteLine(sc.FirstName.DisplayName + " = " + sc.FirstName.Value);
sc.Age.ValueChanged += (from, to) =>
Console.WriteLine("Age changed from " + from + " to " + to);
sc.Age.Value = 39;
// sc.Age = null; compiler would stop this
If you're already using an IOC container you may be able to achieve some of this without going directly to reflection.
It looks like you're trying to create a static extension method?
DateTime yesterday = DateTime.Yesterday(); // Static extension.
Instead of
DateTime yesterday = DateTime.Now.Yesterday(); // Extension on DateTime instance.
If this is what you're trying to pull off, I do not believe it is possible in the current version of C#.
It sounds like you are integrating layers a little too tightly. Normally in this type of situation I would let the presentation layer decide the implementation of GetDisplayName() instead of making it an extension of the property itself. You could create an interface called MyTypeDisplayer or whatever you fancy, and let there be multiple implementations of it not limiting you to a single display implementation.
The issue here is that one cannot get a reference to non-static methods via instance MyType.[Member]. These can only be seen through a reference to an instance of the type. You also cannot build an extension method on-top of a type declaration, only on an instance of a type - that is the extension method itself has to be defined using an instance of a type (this T x).
One can however define the expression like this to get a reference to static members:
((MyType x) => MyType.Property)
One could do something similar to string displayName = ((MyType x) => x.Property).GetDisplayName();
The first issue is guaranteeing that the compiler treats your (x=> x.Property) as an Expression rather than an action/func etc...
To do this one might need to do this:
string displayName = ((Expression<Func<PropertyType>>)((MyType x) => x.Property).GetDisplayName();
The extension method would then have to be defined like this:
public static string GetDisplayName<T>(this Expression<Func<T>> expression)
You might also have to define an extension method on top of Expression<Action>> and Expression<Action<T>> if your members are also methods.
You can do a dot after an Expression - this is where the Compile method would reside.
Appended:
I think the static call to the extension method in cases that one doesn't have an instance of the type one needs to do "reflection" on to determine a Members name would be the cleanest syntax still - this way you could still use the extension method when using an instance of a type and fall back to the static call definition => MyExtensionClass.GetDisplayName(TypeOfX x => TypeOfX.StaticMember OR x.Property/Member) when one doesn't have an instance
If you interface your properties, you could make the extension on the interface instead:
namespace Linq1
{
class Program
{
static void Main(string[] args)
{
MyType o = new MyType();
o.Property.GetDisplayName();
}
}
public class MyType
{
public IDisplayableProperty Property { get; set; }
}
public interface IDisplayableProperty
{
string GetText();
}
public class MyProperty1 : IDisplayableProperty
{
public string GetText() { return "MyProperty2"; }
}
public class MyProperty2 : IDisplayableProperty
{
public string GetText() { return "MyProperty2"; }
}
public static class Extensions
{
public static string GetDisplayName(this IDisplayableProperty o)
{
return o.GetText();
}
}
}