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.
We have a helper function to remove html tags from the string that we want to apply to few properties of our classes like Name, Firstname, Comments etc.
So for that what I am doing right now is removing html tags before assigning value to the property like this
public string Name
{
get { return _dalObj.Name; }
set { _dalObj.Name = Helper.StripHTML(value); }
}
This is working fine!
But I am looking for some better and centralized way to do this rather than applying it to all the properties setter.
So that I will write this code once somewhere centrally and then will mark the properties (may be by custom data annotation or registering them somewhere or using reflection) and those properties will be picked automatically and this code will be applied to there setter.
Is there any way to achieve this or what I am doing is right?
You could always encode it as part of your types!
_dalObj could be some type which declares name as such:
private NoHtmlString _name = ""
with the class NoHtmlString looking something like this:
public class NoHtmlString
{
private readonly string _value;
private NoHtmlString(string str)
{
_value = str;
}
public static implicit operator string(NoHtmlString noHtmlString)
{
return noHtmlString._value;
}
public static implicit operator NoHtmlString(string someString)
{
return new NoHtmlString(StringHelpers.StripHtml(someString));
}
}
This way your outer accessing layers could just do the following:
public string Name
{
get { return _dalObj.Name; }
set { _dalObj.Name = value; }
}
You get the benefit of having something you can implicitly use as a string, but with the guarantee that it will always be stripped of the HTML.
As others have mentioned, this could be achieved using Aspect-Oriented Programming as well.
As mentioned in the comments, it looks like a code smell, that the property will have a different value than the one that was set.
I would suggest to store the value as it is, and implement in the abstract base class a Sanitize() method, which will go trough all those properties and strip the html, it can be done trough reflection for exploring properties to sanitize (e.g. those with some attribute), or it can be an abstract method implemented by each class to sanitize the proper properties.
It seems to me that you need to do some Aspect Oriented Programming.
One AOP tool that you can use with C# is PostSharp. You can use it to create an Aspect, e.g. HtmlStripperAspect and then apply it to your properties.
For example, you would have something like this:
[HtmlStripperAspect]
public string Name
{
get { return _dalObj.Name; }
set { _dalObj.Name = value; }
}
where HtmlStripperAspect is a centralized class that you create with the help of PostSharp and inside such class you call your Helper.StripHTML method.
You can apply the aspect also on the class, namespace, or assembly level if you don't want to decorate all your properties with HtmlStripperAspect.
Take a look at PostSharp documentation on how exactly this is done.
PostSharp is a compile-time AOP tool, it injects IL code into your assemblies at compile time. If you don't like this, there are run-time AOP tools such as Dynamic Proxy.
Pretty simple question really, should I use my properties to initialize fields in the constructor or reference them directly?
Example:
public class Foo()
{
private string example;
public String Example
{
get/set etc..
}
public Foo(string exampleIn)
{
Example = exampleIn;
}
}
Or is it better practice to do this:
public class Foo()
{
private string example;
public String Example
{
get/set etc..
}
public Foo(string exampleIn)
{
example = exampleIn;
}
}
Either way, I don't think either would violate encapsulation so I am wondering if there is a preferred way to go?
There is really no right or wrong answer here (and because of that I am almost tempted to vote to close). But, I tend to agree with Jacob on this. I prefer the property getter and setter route especially now that we have automatic properties. Do keep in mind that you can have different access modifies on the getters and setters in case that influences your decision for any reason. I mean, if you are going to use the property in the constructor then try to be consistent and use it exclusively everywhere else in the class as well. That may mean that you do not want to expose the setter to the outside.
public class Foo()
{
private string example;
public String Example
{
get { return example; }
private set { example = value; }
}
public Foo(string exampleIn)
{
Example = exampleIn;
}
}
Before automatic properties, which were introduced in C# 3.0, your second example is more "proper" in my opinion. Now with automatic properties I think this is best:
public class Foo()
{
private string example;
public String Example
{
{ get; set; }
}
public Foo(string exampleIn)
{
Example = exampleIn;
}
}
It depends on whether the data value will further be processed inside the Setter. IF the value needs processing then it's better to use what #Jacob has said but if the value will not be further processed (which is the case in most scenarios), it's better to use the private member to avoid an extra method call to setter method. When CLR compiles the code, it create two methods for Get and Set property and using the Property to access/modify the value which defines the property will result in extra method call unnecessarily (if the value is not processed further).
Sometimes you have a private field that backs a property, you only ever want to set the field via the property setter so that additional processing can be done whenever the field changes. The problem is that it's still easy to accidentally bypass the property setter from within other methods of the same class and not notice that you've done so. Is there a way in C# to work around this or a general design principle to avoid it?
IMHO, it is not used, because:
The class must trust itself
If your class gets as large that one part does not know the other, it should be divided.
If the logic behind the property is slightly more complex, consider to encapsulate it in an own type.
I'd consider this a nasty hack and try to avoid it if possible, but...
You can mark the backing field as obsolete so that the compiler will generate a warning when you try to access it, and then suppress that warning for the property getter/setter.
The warning codes that you'd need to suppress are CS0612 for the plain Obsolete attribute and CS0618 if the attribute has a custom message.
[Obsolete("Please don't touch the backing field!")]
private int _backingField;
public int YourProperty
{
#pragma warning disable 612, 618
get { return _backingField; }
set { _backingField = value; }
#pragma warning restore 612, 618
}
There's no inbuilt way to do what you want to do, but by the sounds of things you need another layer of abstraction between your class and that value.
Create a separate class and put the item in there, then your outer class contains the new class, and you can only access it through its properties.
No, there isn't. I'd quite like this myself - something along the lines of:
public string Name
{
private string name; // Only accessible within the property
get { return name; /* Extra processing here */ }
set { name = value; /* Extra processing here */ }
}
I think I first suggested this about 5 years ago on the C# newsgroups... I don't expect to ever see it happen though.
There are various wrinkles to consider around serialization etc, but I still think it would be nice. I'd rather have automatically implemented readonly properties first though...
You CAN do this, by using a closure over a local in the constructor (or other initialisation function). But it requires significantly more work that the helper class approach.
class MyClass {
private Func<Foo> reallyPrivateFieldGetter;
private Action<Foo> reallyPrivateFieldSetter;
private Foo ReallyPrivateBackingFieldProperty {
get { return reallyPrivateFieldGetter(); }
set { reallyPrivateFieldSetter(value); }
}
public MyClass() {
Foo reallyPrivateField = 0;
reallyPrivateFieldGetter = () => { return reallyPrivateField; }
reallyPrivateFieldSetter = v => { reallyPrivateField = v; };
}
}
I suspect that the underlying field type Foo will need to be a reference class, so the two closures are created over the same object.
There is no such provisioning in C#.
However I would name private variables differently (e.g. m_something or just _something) so it is easier to spot it when it is used.
You can put all of your private fields into a nested class and expose them via public properties. Then within your class, you instantiate that nested class and use it. This way those private fields are not accessible as they would have been if they were part of your main class.
public class A
{
class FieldsForA
{
private int number;
public int Number
{
get
{
//TODO: Extra logic.
return number;
}
set
{
//TODO: Extra logic.
number = value;
}
}
}
FieldsForA fields = new FieldsForA();
public int Number
{
get{ return fields.Number;}
set{ fields.Number = value;}
}
}
It just provides a level of obstruction. The underlying problem of accessing private backing fields is still there within the nested class. However, the code within class A can't access those private fields of nested class FieldForA. It has to go through the public properties.
Perhaps a property backing store, similar to the way WPF stores properties?
So, you could have:
Dictionary<string,object> mPropertyBackingStore = new Dictionary<string,object> ();
public PropertyThing MyPropertyThing
{
get { return mPropertyBackingStore["MyPropertyThing"] as PropertyThing; }
set { mPropertyBackingStore["MyPropertyThing"] = value; }
}
You can do all the pre-processing you want now, safe in the knowledge that if anyone did access the variable directly, it would have been really really hard compared to the property accessor.
P.S. You may even be able to use the dependency property infrastructure from WPF...
P.P.S. This is obviously going to incur the cost of casting, but it depends on your needs - if performance is critical, perhaps this isn't the solution for you.
P.P.P.S Don't forget to initialise the backing store! (;
EDIT:
In fact, if you change the value property stored to a property storage object (using the Command pattern for example), you could do your processing in the command object...just a thought.
Can't do this in standard C#, however you could
define a custom attribute say OnlyAccessFromProperty
write your code like
[OnlyAccessFromProperty(Name)]
String name
Name
{
get{return name;}
}
etc …
Then write a custom rule for FxCop (or another checker)
Add FxCop to your build system so if your custom rule find an error the build is failed.
Do we need a set of standard custom rules/attributes to enforce common design patens like this without the need to extend C#
C# has no language feature for this. However, you can rely on naming conventions, similar to languages which have no private properties at all. Prefix your more private variable names with _p_, and you'll be pretty sure that you don't type it accidentally.
I don't know C# but in Java you may have a base class with only private instance variables and public setters and getters (should return a copy of the instance var.) and do all other in an inherited class.
A "general design principle" would be "use inheritance".
There is no build in solution in C#, but I think your problem can be solved by good OO design:
Each class should have a single purpose. So try to extract the logic around your field into a class as small as possible. This reduces the code where you can access the field by accident. If you do such errors by accident, your class is probably to big.
Often interface are good to restrict access to only a certain "subset" of an object. If that's appropriate for your case depends on your setting of course. More details about the work to be done would help to provide a better answer.
You say that you do additional processing. Presumably this would be detectable under the correct conditions. My solution, then, would be to create unit tests that implement conditions such that if the backing field is used directly the test will fail. Using these tests you should be able to ensure that your code correctly uses the property interface as long as the tests pass.
This has the benefit that you don't need to compromise your design. You get the safety of the unit tests to ensure that you don't accidently make breaking changes and you capture the understanding of how the class works so that others who come along later can read your tests as "documentation."
Wrap it in a class? The property thing is a bit like that anyway, associating data with methods - the "Encapsulation" they used to rave about...
class MyInt
{
private int n;
public static implicit operator MyInt(int v) // Set
{
MyInt tmp = new MyInt();
tmp.n = v;
return tmp;
}
public static implicit operator int(MyInt v) // Get
{
return v.n;
}
}
class MyClass
{
private MyInt myint;
public void func()
{
myint = 5;
myint.n = 2; // Can't do this.
myint = myint + 5 * 4; // Works just like an int.
}
}
I'm sure I'm missing something? It seems too normal...
BTW I do like the closures one, superbly mad.
My favorite solution to this (and what I follow) is to name private backing fields that are never intended to be used directly with a leading underscore, and private fields that are intended to be used without the underscore (but still lowercase).
I hate typing the underscore, so if I ever start to access a variable that starts with the underscore, I know somethings wrong - I'm not supposed to be directly accessing that variable. Obviously, this approach still doesn't ultimately stop you from accessing that field, but as you can see from the other answers, any approach that does is a work around and/or hardly practical.
Another benefit of using the underscore notation is that when you use the dropdown box to browse your class, it puts all of your private, never-to-be-used backing fields all in one place at the top of the list, instead of allowing them to be mixed in with their respective properties.
As a design practice, you could use a naming convention for "private properties" that's different from normal public members - for instance, using m_ItemName for private items instead of ItemName for public ones.
If you're using the C# 3.0 compiler you can define properties which have compiler-generated backing fields like this:
public int MyInt { get; set; }
That will mean there is only one way to access the property, sure it doesn't mean you can only access the field but it does mean that there's nothing but the property to access.
I agree with the general rule that the class should trust itself (and by inference anybody coding within the class).
It is a shame that the field is exposed via intellisense.
Sadly placing [EditorBrowsable(EditorBrowsableState.Never)] does not work within that class (or indeed the assembly(1))
In Visual C#, EditorBrowsableAttribute does not suppress members from a class in the same assembly.
If you really do wish to solve this aspect of it the the following class may be useful and makes the intent clear as well.
public sealed class TriggerField<T>
{
private T data;
///<summary>raised *after* the value changes, (old, new)</summary>
public event Action<T,T> OnSet;
public TriggerField() { }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(T initial) { this.data=initial; }
public TriggerField(Action<T,T> onSet) { this.OnSet += onSet; }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(Action<T,T> onSet, T initial) : this(onSet)
{
this.data=initial;
}
public T Value
{
get { return this.data;}
set
{
var old = this.data;
this.data = value;
if (this.OnSet != null)
this.OnSet(old, value);
}
}
}
Allowing you to (somewhat verbosely) use it like so:
public class Foo
{
private readonly TriggerField<string> flibble = new TriggerField<string>();
private int versionCount = 0;
public Foo()
{
flibble.OnSet += (old,current) => this.versionCount++;
}
public string Flibble
{
get { return this.flibble.Value; }
set { this.flibble.Value = value; }
}
}
alternatively you can go for a less verbose option but accessing Flibble is by the not idiomatic bar.Flibble.Value = "x"; which would be problematic in reflective scenarios
public class Bar
{
public readonly TriggerField<string> Flibble;
private int versionCount = 0;
public Bar()
{
Flibble = new TriggerField<string>((old,current) => this.versionCount++);
}
}
or solution if you look at the community content!
The new Lazy class in .net 4.0
provides support for several common
patterns of lazy initialization
In my experience this is the most common reason I wish to wrap a field in a private properly, so solves a common case nicely. (If you are not using .Net 4 yet you can just create your own “Lazy” class with the same API as the .Net 4 version.)
See this and this and this for details of using the Lazy class.
Use the "veryprivate" construct type
Example:
veryprivate void YourMethod()
{
// code here
}
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