"Catchall" Properties in C#? - c#

Is it possible to create a "catchall" getter property in C#?
class xyzFactory {
public static object this.*(string name){
get { return new name();}
}
}
In PHP you would write something like
//static getters are new to 5.3, so I didn't put it here.
class xyzFactory{
public _get($name){ return $name();}
}

Not in C# 3. In C# 4.0 you could achieve something like this with expando properties and the dynamic keyword.

You can achieve this with a hack like
xyzFactory.Instance.Name
where static Instance property is of type dynamic
And make you xyzFactory derived from DynamicObject class.
public xyzFactory : DynamicObject
{
private static xyzFactory _instance = new xyzFactory();
private xyzFactory() { }
public static dynamic Instance
{
get{ return _instance; }
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
// ...
}
}

No, you can't do that in C#. C# is a compiled language and statically resolves method slots at compile time. It doesn't support passing the property name as string or things like that.

The closest you can get is overload index operator ([]). At least until C# 4.0 is out

You could use the property pattern to implement this, as others have said C# won't currently help you implement it though

You may be able to do this with LinFu. It uses a dynamic Proxy to allow for Duck Typing and Late Binding, Ruby-style Mixins

Related

How to make Option classes like GUILayoutOption?

I'm wondering how to make a class similar to GUILayoutOption class where it would take a whole bunch of GUILayout's static fields as parameters.
I couldn't find my answer in Unity Docs and I was wondering if somebody has made such a construct before.
I'm trying to make something like this:
public void SomeMethod( params MyClassOption[] options )
and call it for example like this: SomeMethod(MyClass.AnimationClip(aniClipRef), MyClass.AnimationDuration(duration), MyClass.StopAllOtherAnimations);
Seems like a great and clean way to wrap code with dozens of potentially optional parameters, but I'm not sure how to define it. Can somebody write a minimalistic example or explain how it works?
You won't find stuff like these in the documentation or any tutorial. If you are curious on how something is implemented, use decompiler such as .NET Reflector and you will see how each class is implemented.
Below is a minimalist example of how to do this. Do not use this. This is only here to show exactly how this is done by Unity. It uses the param keyword and performs boxing, both which allocates memory.
Example:
MyClass.Button("Submit Button", MyClass.MinWidth(10), MyClass.MaxWidth(20),
MyClass.MinHeight(10), MyClass.MaxHeight(10));
The MyClassOption class:
public class MyClassOption
{
public Type type;
public object value;
public MyClassOption(Type type, object value)
{
this.type = type;
this.value = value;
}
public enum Type
{
minWidth,
maxWidth,
minHeight,
maxHeight,
}
}
The MyClass class:
public class MyClass
{
public static bool Button(string text, params MyClassOption[] options)
{
return showButton(text, options);
}
private static bool showButton(string text, MyClassOption[] options)
{
//Not IMPLEMENTED
//DISPLAY BUTTON THEN CHECK IF IT IS CLICKED?
return false;
}
public static MyClassOption MaxHeight(float maxHeight)
{
return new MyClassOption(MyClassOption.Type.maxHeight, maxHeight);
}
public static MyClassOption MaxWidth(float maxWidth)
{
return new MyClassOption(MyClassOption.Type.maxWidth, maxWidth);
}
public static MyClassOption MinHeight(float minHeight)
{
return new MyClassOption(MyClassOption.Type.minHeight, minHeight);
}
public static MyClassOption MinWidth(float minWidth)
{
return new MyClassOption(MyClassOption.Type.minWidth, minWidth);
}
}
Basically, you add your custom options in the enum from the MyClassOption class then you add a function that will be used to access that enum in the MyClass. That function will return new MyClassOption object.
There's too much memory allocation going on each time an option is added to a function or executed to the extent that I think it is not worth it. It is fine in a normal C# application but not in a game app which can cause hiccups due to GC.
EDIT:
Things that can be done to improve this:
1.Change the MyClassOption class to struct.
2.On the MyClassOption class constructor object value parameter, change that to c# generics. T[] value.
Now, the only problem left is the param keyword which is the only thing that allocates memory. It should be fine for some applications but this is mostly useful for Editor plugins.

how to write the methods inside the enum in c# [duplicate]

In Java, it's possible to have methods inside an enum.
Is there such possibility in C# or is it just a string collection and that's it?
I tried to override ToString() but it does not compile. Does someone have a simple code sample?
You can write extension methods for enum types:
enum Stuff
{
Thing1,
Thing2
}
static class StuffMethods
{
public static String GetString(this Stuff s1)
{
switch (s1)
{
case Stuff.Thing1:
return "Yeah!";
case Stuff.Thing2:
return "Okay!";
default:
return "What?!";
}
}
}
class Program
{
static void Main(string[] args)
{
Stuff thing = Stuff.Thing1;
String str = thing.GetString();
}
}
You can write an extension method for your enum:
How to: Create a New Method for an Enumeration (C# Programming Guide)
Another option is to use the Enumeration Class created by Jimmy Bogard.
Basically, you must create a class that inherits from his Enumeration. Example:
public class EmployeeType : Enumeration
{
public static readonly EmployeeType Manager
= new EmployeeType(0, "Manager");
public static readonly EmployeeType Servant
= new EmployeeType(1, "Servant");
public static readonly EmployeeType Assistant
= new EmployeeType(2, "Assistant to the Regional Manager");
private EmployeeType() { }
private EmployeeType(int value, string displayName) : base(value, displayName) { }
// Your method...
public override string ToString()
{
return $"{value} - {displayName}!";
}
}
Then you can use it like an enum, with the possibility to put methods inside it (among another things):
EmployeeType.Manager.ToString();
//0 - Manager
EmployeeType.Servant.ToString();
//1 - Servant
EmployeeType.Assistant.ToString();
//2 - Assistant to the Regional Manager
You can download it with NuGet.
Although this implementation is not native in the language, the syntax (construction and usage) is pretty close to languages that implement enums natively better than C# (Kotlin for example).
Nope. You can create a class, then add a bunch of properties to the class to somewhat emulate an enum, but thats not really the same thing.
class MyClass
{
public string MyString1 { get{ return "one";} }
public string MyString2 { get{ return "two";} }
public string MyString3 { get{ return "three";} }
public void MyMethod()
{
// do something.
}
}
A better pattern would be to put your methods in a class separate from your emum.
Since I came across, and needed the exact opposite of enum to string, here is a Generic solution:
static class EnumExtensions {
public static T GetEnum<T>(this string itemName) {
return (T) Enum.Parse(typeof(T), itemName, true);
}
}
This also ignores case and is very handy for parsing REST-Response to your enum to obtain more type safety.
Hopefully it helps someone
C# Does not allow use of methods in enumerators as it is not a class based principle, but rather an 2 dimensional array with a string and value.
Use of classes is highly discouraged by Microsoft in this case, use (data)struct(ures) instead; The STRUCT is intended as a light class for data and its handlers and can handle functions just fine. C# and its compiler don't have the tracking and efficiency capabilities as one knows from JAVA, where the more times a certain class / method is used the faster it runs and its use becomes 'anticipated'. C# simply doesn't have that, so to differentiate, use STRUCT instead of CLASS.

Adding an extension method to Property Accessor

We are doing alot of INotifyPropertyChanged implementation in our View Models and quite frankly are getting tired of having to fire the property changed events explicitly in our code for both inconvenience and aesthetic reasons.
I want to put an extension on the setter of our property, making the resulting code look like:
public string LazyAccessor
{
get;
set.notify();
}
Is there a way to do this? Can we invent one if there isn't?
Check out NotifyPropertyWeaver. This will modify your code during the build process to have your properties implement the INotifyPropertyChanged pattern.
This is available as a Visual Studio Extension
Aspect oriented programming could be solution of your problem.
See Aspect Oriented Programming in C#.
And some examples here: http://www.codeproject.com/Articles/337564/Aspect-Oriented-Programming-Using-Csharp-and-PostS
Your "set.notify()" could work with some Reflection, but I donĀ“t think this would be good solution and you will still need to implement getter and setter.
Extension methods can only be added to types. The getters and setters on automatic properties are converted into methods with backing variables by the compiler, so there is no way to put an extension method on them.
Is there a way to do this?
No, there isn't, not like you posted. Extension methods operate on types, not getters or setters.
Can we invent one if there isn't?
That would require changes to the C# specification - not a likely thing to happen.
There are other approaches that you can take to ease this - using a base class with a method that will make the boiler plate calls for you for example.
They didn't make it into 4.0, but are rumored to be included in 5.0.
I found this approach helpful.
You couldn't do it on the set itself. That is an action. You might however be able to do this:
public static class extensions()
{
public static NotifyAccessorSet(this string value) { some code }
}
public class SomeClass()
{
.....
private string mAccessor;
public string LazyAccessor{
get { return mAccessor; }
set { mAccessor = value; mAccessor.NotifyAccessorSet(); }
}
}
It's somewhat off the top of my head and keep in mind that the extension method would apply to all types string so you might want to implement your own return type and apply the extension method to it. Return that type then from lazyaccessor.
you can emulate a 'property-like' behavior without calling the event manualy by overriding the conversion operators of a custom generic struct.
The following is my solution:
public struct column<TType>
{
private TType _value;
private column(TType value) : this()
{
_value = value;
}
private void Set(TType value)
{
// Implement your custom set-behavior...
}
private TType Get()
{
// Implement your custom get-behavior...
return _value;
}
public override string ToString()
{
return _value.ToString();
}
public static implicit operator column<TType>(TType p)
{
column<TType> column = new column<TType>(p);
column.Set(p);
return column;
}
public static implicit operator TType(column<TType> p)
{
return p.Get();
}
}
I declare the struct with a generic parameter to avoid from conversion errors. You can use it like this:
public class Test
{
public column<int> kKey;
public column<float> dMoney;
public column<string> cValue;
public Test()
{
kKey = 42;
dMoney = 3.1415926f;
cValue = "May the force be with you!";
}
}
...I know, the question is outdated but it may help someone in the future.

I want a dynamic static field

I've got a class A with a public field b
class A
{
public static string b;
}
but now I want to make b dynamic so I call it anything. So I can make the class a DynamicObject
class A : DynamicObject
{
}
but I the compiler doesn't let me now call A.dynamicThing cos I have to instantiate A as dynamic.
How can I mangle c# further to make this work?
I don't belive you're going to find a way to make this work. It's not just the DynamicObject that makes things work. The declaration as a variable of the "dynamic" data type is what tells the compiler to actually use the DynamicObject base to resolve the member access. With static access direct to the class, you don't have that. So I really just don't think this is going to work in C# unless that changes in the future.
It's not possible right now with .NET 4
more information in this article.
I think I understand now - the closest you can get is by using an ExpandoObject :
dynamic foo = new ExpandoObject();
foo.somethinghere = "bar";
foo.dynamicThing = "baz";
Edit:
I don't think its possible to re-route the access to a static property of a class
to an expando object if the name of the property does not match - how would the compiler know that that's what you meant to do? You are getting a compile time error after all, not a runtime error.
From MSDN:
When a field, method, property, event,
operator, or constructor declaration
includes a static modifier, it
declares a static member. In addition,
a constant or type declaration
implicitly declares a static member.
Static members have the following
characteristics:
When a static member M is referenced in a member-access (Section 7.5.4)
of the form E.M, E must denote a type containing M.
...
public class FakeDynamicMethodInvoker : DynamicObject
{
// your code here
}
public class FakeDynamicWrapper<T>
{
static FakeDynamicWrapper()
{
DynamicStaticField = (dynamic)new FakeDynamicMethodInvoker();
}
public static T DynamicStaticField{ get; set; }
}
public class RealClassWithDynamicStaticField: FakeDynamicWrapper<dynamic>
{
}
somewhere in a code:
RealClassWithDynamicStaticField.DynamicStaticField.AnyMethod();
C# doesn't let you really rename variables to some dynamic name at runtime. Your question is mangled.
If you are wanting variable b to have a dynamic object at runtime, then use the dynamic keyword.
Example:
dynamic b = GetBValue();
b.SomeOperation(); // the type of "b" will be evaluated/chosen at runtime.
Old question but worth to answer :)
Static constructors are the answer to these problems.
https://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx
public class MyClass
{
public static dynamic StaticDynamicObject;
static MyClass()
{
StaticDynamicObject = new ExpandoObject();
StaticDynamicObject.Prop = "woohoo!";
}
}

How can I port this Java code to C#?

I am looking at a pattern implemented in Java and have some questions about how it aligns to (can be ported to) C#.
Java:
class Foo
{
private Class someClass;
...
}
class Bar
{
private Field some Field;
}
First, Class stores an instance of a domain object. It looks like Java exposes reflection methods on the type which are used to access fields on the object through reflection. What would type would be synonymous in C#? Would I use object and then use MethodInfo or is there a better way?
Second, Field is type in the framework and is assigned by using:
someClass.getDeclaredField(fieldName)
Is there a parallel in the .NET framework i should use?
Right now I created a custom object in place of the Class in Foo, and I created a custom object for Field. Is there a preferred way to do this?
You may take a look at the FieldInfo type and GetField method.
Code might look something among the lines:
class Foo
{
public Type someClass;
...
}
class Bar
{
private FieldInfo some_Field;
public Assign(string fieldName)
{
Foo foo = new Foo();
some_Field = foo.someClass.GetField(fieldName);
}
}
You may also get the value of the field by using:
foo.GetType().GetField("name").GetValue(foo).ToString()
In this example, we assume class foo has a field named "name". What does this help? Well think it as this way:
private string getValueOfUnknownField(string fieldName)
{
return(foo.GetType().GetField(fieldName).GetValue(foo).ToString());
}
Even if you change class foo and add new fields to it, you don't need to change getValueOfUnknownField method.

Categories

Resources