Is it possible to implement properties in languages other than C#? - c#

During a bout of C# and WPF recently, I got to like C#'s properties:
public double length_inches
{
get { return length_metres * 39.0; }
set { length_metres = value/39.0; }
}
Noticing, of course, that length_metres may change from being a field to a property, and the code need not care. WPF can also bind UI elements to object properties very happily.
When I first learnt about classes and objects, I assumed that there was a way to do it, because it seemed so obvious! The point of hiding complexity inside a class is that you don't need to care what is being stored any more. But it has taken until now to see it.
Amusingly, I first saw it done in VB.Net. That leading edge of OO purity.
The question is, can I recreate properties in other languages which I use more often, like javascript, python, php? In javascript, if I set a variable to a closure, won't I get the closure back again, rather than the result of it?

Python definitely supports properties:
class Foo(object):
def get_length_inches(self):
return self.length_meters * 39.0
def set_length_inches(self, val):
self.length_meters = val/39.0
length_inches = property(get_length_inches, set_length_inches)
Starting in Python 2.5, syntactic sugar exists for read-only properties, and in 2.6, writable ones as well:
class Foo(object):
# 2.5 or later
#property
def length_inches(self):
return self.length_meters * 39.0
# 2.6 or later
#length_inches.setter
def length_inches(self, val):
self.length_meters = val/39.0

In JavaScript:
var object = {
// .. other property definitions ...
get length_inches(){ return this.length_metres * 39.0; },
set length_inches(value){ this.length_metres = value/39.0; }
};

In C# properties are mostly just a compiler feature. The compiler generates special methods get_PropertyName and set_PropertyName and works out the calls and so forth. It also set the specialname IL property of the methods.
If your language of choice supports some kind of preprocessor, you can implement something similar but otherwise you're pretty much stuck with what you got.
And of course, if you're implementing your own .NET language you can do what the C# compiler does as well.
Due to the implementation details, there are actually subtle differences between fields and properties. See this question for details.

Delphi, from which C# is derived, has had properties from the word go. And the word go was about 15 years ago.

Most dynamic languages support something like that. In Smalltalk and Ruby, fields are not directly exposed - The only way to get at them is through a method. In other words - All variables are private. Ruby has some macros (class methods really), to make it simpler to type:
class Thing
attr_accessor :length_inches
end
will make a getter and a setter for length_inches. Behind the scenes, it's simply generating this:
class Thing
def length_inches
#length_inches
end
def length_inches=(value)
#length_inches = value
end
end
(Ruby crash-course: The # prefix means it's an instance variable. return is implicit in Ruby. t.length_inches = 42 will automatically invoke length_inches=(42), if t is a Thingy.)
If you later on want to put some logic in the getters/setters, you can simply manually implement the same methods:
class Thing
def length_inches
#length_metres * 39.0
end
def length_inches=(value)
#length_metres = value / 39.0
end
end

Out of the box in VB (that's VB 6.0, not VB.net) and VBScript!
Public Property Get LengthInches() As Double
LengthInches = LengthMetres * 39
End Property
Public Property Let LengthInches(Value As Double)
LengthMetres = Value / 39
End Property
Also possible to fake quite nicely in PHP creating a class that you extend in combination with naming guidelines, protected members and magic functions. Yuch.

Delphi has a property pattern (with Setter and Getter methods), which also can be used in interfaces. Properties with "published" visibility also will be displayed in the IDE object inspector.
A class definition with a property would look like this:
TFoo = class
private
FBar: string;
procedure SetBar(Value: string);
function GetBar: string;
public
property Bar: string read GetBar write SetBar;
end;
or (without Setter / Getter):
TFoo = class
private
FBar: string;
public
property Bar: string read FBar write FBar;
end;

I think this is the Python equivalent
class Length( object ):
conversion = 39.0
def __init__( self, value ):
self.set(value)
def get( self ):
return self.length_metres
def set( self, value ):
self.length_metres= value
metres= property( get, set )
def get_inches( self ):
return self.length_metres*self.conversion
def set_inches( self, value ):
self.length_metres= value/self.conversion
inches = property( get_inches, set_inches )
It works like this.
>>> l=Length(2)
>>> l.metres
2
>>> l.inches
78.0
>>> l.inches=47
>>> l.metres
1.2051282051282051

In Objective-C 2.0 / Cocoa:
#interface MyClass : NSObject
{
int myInt;
NSString *myString;
}
#property int myInt;
#property (nonatomic, copy) NSString *myString;
#end
Then in the implementation, simply specify:
#synthesize myInt, myString;
This generates the accessors for that member variable with key-value-coding compliant naming conventions like:
- (void)setMyString:(NSString *)newString
{
[myString autorelease];
myString = [newString copy];
}
Saves a lot of work typing out your accessors.

It's definitely possible to implement properties in other languages. VB and F# for example have explicit property support. But these both target the CLR which has property support.
VB.
Public Property Name As String
Get
return "someName"
End Get
Set
...
End Set
End Property
I do not believe javascript or PHP supports property syntax but I'm not very familiar with those languages. It is possible to create field get/set accessor methods in pretty much any language which simulate properties.
Under the hood, .Net properties really just result down to get/set methods. They just have a really nice wrapper :)

ActionScript 3 (javascript on steroids) has get/set syntax also

Sadly, I haven't tried it myself yet, but I read that it was possible to implement properties in PHP through __set and __get magic methods. Here's a blog post on this subject.

You can make something like it with PHP5 magic functions.
class Length {
public $metres;
public function __get($name) {
if ($name == 'inches')
return $this->metres * 39;
}
public function __set($name, $value) {
if ($name == 'inches')
$this->metres = $value/39.0;
}
}
$l = new Length;
$l->metres = 3;
echo $l->inches;

When I first played with Visual Basic (like, version 1 or something) the first thing I did was try to recreate properties in C++. Probably before templates were available to me at the time, but now it would be something like:
template <class TValue, class TOwner, class TKey>
class property
{
TOwner *owner_;
public:
property(TOwner *owner)
: owner_(owner) {}
TValue value() const
{
return owner_->get_property(TKey());
}
operator TValue() const
{
return value();
}
TValue operator=(const TValue &value)
{
owner_->set_property(TKey(), value);
return value;
}
};
class my_class
{
public:
my_class()
: first_name(this), limbs(this) {}
struct limbs_k {};
struct first_name_k {};
property<std::string, my_class, first_name_k> first_name;
property<int, my_class, limbs_k> limbs;
std::string get_property(const first_name_k &);
void set_property(const first_name_k &, const std::string &value);
int get_property(const limbs_k &);
void set_property(const limbs_k &, int value);
};
Note that the "key" parameter is ignored in the implementations of get_property/set_property - it's only there to effectively act as part of the name of the function, via overload resolution.
Now the user of my_class would be able to refer to the public members first_name and limbs in many situations as if they were raw fields, but they merely provide an alternative syntax for calling the corresponding get_property/set_property member functions.
It's not perfect, because there are some situations where you'd have to call value() on a property to get the value, whenever the compiler is unable to infer the required type conversion. Also you might get a warning from the passing of this to members in the constructor, but you could silence that in this case.

Boo is a .NET language very similar to Python, but with static typing. It can implement properties:
class MyClass:
//a field, initialized to the value 1
regularfield as int = 1 //default access level: protected
//a string field
mystringfield as string = "hello"
//a private field
private _privatefield as int
//a public field
public publicfield as int = 3
//a static field: the value is stored in one place and shared by all
//instances of this class
static public staticfield as int = 4
//a property (default access level: public)
RegularProperty as int:
get: //getter: called when you retrieve property
return regularfield
set: //setter: notice the special "value" variable
regularfield = value
ReadOnlyProperty as int:
get:
return publicfield
SetOnlyProperty as int:
set:
publicfield = value
//a field with an automatically generated property
[Property(MyAutoProperty)]
_mypropertyfield as int = 5

You could do it in all sorts of languages, with varying degrees of syntactic sugar and magic. Python, as already mentioned, provides support for this (and, using decorators you could definitely clean it up even more). PHP could provide a reasonable facsimile with appropriate __get() and __set() methods (probably some indirection to. If you're working with Perl, you could use some source filters to replicate the behaviour. Ruby already requires everything to go through.

The convention is to implement a get_PropertyName() and a set_PropertyName() method (that's all it is in the CLR as well. Properties are just syntactic sugar in VB.NET/C# - which is why a change from field to property or vice-versa is breaking and requires client code to recompile.
public int get_SomeValue() { return someValue; }
public void set_SomeValue(int value) { someValue = value; }
private int someValue = 10;
// client
int someValue = someClass.get_SomeValue();
someClass.set_SomeValue(12);

Related

How is a property without a set allowed (read-only property) is being set inside the class? What mechanism?

First of all, I'm NOT really familiar with C#, but I am with C++. I didn't find any info about this. Through what mechanism is a C# property is being set when it only have a get implemented and the set is hidden. It's a read-only property that is being set continuously, inside a loop.
My hunch is that the get returns a reference which C# uses to set the value in this case. Is that correct?
(I've come across a code which I'm trying to understand)
For example:
public Series<double> Avg
{
get { return Values[1]; }
}
public Series<double> Default
{
get { return Values[0]; }
}
(Series is just an array of doubles, but accessing them from the end of the array, by index)
The code in RSI does write the items of the array:
Default[0] = value0;
Avg[0] = constant1 * value0 + constant2 * Avg[1];
So what is happening up there? Just to understand, it is something like the below C++ code?
double& Avg(int index)
{
return Values[index+1];
}
Certainly, in C++ you would use Avg(1) instead of Avg[1] since it is a function, I'm just curious what the logic actually does in #RSI.cs. Is the get in this case is like a reference so it can also write values via the get or is the set is auto-implemented so writing and reading the above properties is accessing a completely different index or even variable?
Are the above C# samples even a valid C# code?
That means you can only read the value of the property but not write it from the outside.
Take a file class for example. It would have a property FileSize that you could read from the outside. It would make no sense to have a Setter since setting the file size should not be possible (you have to modify the content of the file in order for the file size to change).
You would then implement a read only property in the form of the following:
public long FileSize { get { return Content.Length; } }
You can compare a C# property to a set of C++ methods.
A get would be a getProperty() method in your C++ class and a set would be a setProperty(value).
A C# property is actually not very different from having a field and two methods. The whole get and set is just a nice way to let the compiler generate this for you.
This means that this is a property that you want it to be read from outside the object without modifying it, for example you can do this:
public class MyObject
{
private string _currentState;//This will be changed only from inside class
public string MyCurrentState
{
get
{
return _currentState;
}
}
}
Since you are more familiar with c++, let me try to translate it somehow. Forgive me any detail errors because it's been some time since I used C++ on a regular basis.
template<class T> class Series
{
// some template class definition
// the index operator in c++
T& operator [](int idx)
{
return somePrivateTArray[idx];
}
}
class UserOfSeries
{
Series<double> Values[]; // = ... somewhere
public:
Series<double>& Avg()
{
return Values[1];
}
Series<double>& Default()
{
return Values[0];
}
}
When you use it, you will probably write
UserOfSeries* aUserOfSeries = getUserOfSeriesFromTheSystem();
Series<double>& theAvg = aUserOfSeries->Avg();
theAvg[4] = 12000.000;
You can set a property without a set. It only means you cannot access it from outside the class (visibility). Inside the class, the get acts as a reference as I write the values, so setting happens throughout the get if you will.
It means that my original C++ example is correct but a more accurate one is (by Rotem)
std::vector& GetAvg() { return Values[0]; }
so writing happens like this:
GetAvg()[0] = ...;
Thank you Oliver and Rotem for your effort in trying understanding my answer. I feel like this is a good and supporting community. The ones who misunderstood my question as a visibility question were downvoting this though :-)

Other equivalent to enum?

I like to use enum as value holders whereever possible and I like it. It is easy to use i.e. just put a dot and see values. It is a good replacement of hard code some time.
But still it has some limitations. We cannot put special characters in values and some other.
Actually I am trying to make code reusable. Please guide me. Is there some technique or way that I can use some data structure like enum that is flexible but have no limitations.
You could use constants; they are immutable and can have any value.
See also: http://msdn.microsoft.com/en-us/library/ms173119.aspx
If I cannot use an enum for a set of predefined values, I use a class of static constants. They look much the same in use, but the values can be anything from a decimal to a string to a struct or class. I've done this for predefined cell color schemes in GridViews, much like the built-in Color class has predefined constant values. Mathematical and scientific constants such as e and Pi (if you wanted different values than are provided by the Math class), or the acceleration of gravity (9.8m/s2), or the speed of light (299,792,458m/s), can also be specified in this way.
If you think you can't use Enums because you need to store predefined string values, try this handy trick using the System.ComponentModel Description attribute:
public Enum MyStrings
{
[Description("This is string one")] StringOne,
[Description("This is a different string")] StringTwo,
...
}
To get the strings out, you simply examine the Description attribute, the code for which is a little messy but can be easily hidden behind an extension method:
public static string GetDescription(this Enum enumValue)
{
object[] attr = enumValue.GetType().GetField(enumValue.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false);
return (attr.Length > 0)
? ((DescriptionAttribute) attr[0]).Description
: String.Empty;
}
Usage:
var stringOne = MyStrings.StringOne.GetDescription(); //"This is string one"
In this case, you can also consider using a Resource file. The value of the string can be changed from outside the scope of the program, without a recompile.
Not sure what exactly you need (re: "special characters"), but you could simply use some constants and put them into a static class, e.g:
public static class MyConstants
{
/// <summary>documentation here</summary>
public const string ValueA = "somevalue";
/// <summary>documentation here</summary>
public const string ValueB = "something else with special characters &#";
// etc.
}
Usage:
var x = MyConstants.ValueB;
One issue you might find with enums and more especially constants is that if you change the source assembly which defines the enum or constant, but don't recompile dependent assemblies, you'll end up mismatching in the source and dependent assemblies. For example:
public const int myConst = 5;
You later change this to:
public const int myConst = 10;
In the source assembly, which was rebuilt, it's 10. But it's 5 in any dependent assemblies that were not rebuilt.
To avoid this, use readonly instead of const. For example:
public readonly int myConst = 5;
This is different than a const, which is more like a C++ #define which causes the value to be placed directly in code. Readonly will cause a lookup at runtime, so if you don't recompile your dependent assemblies you'll still get the correct, updated value.

Is it possible to step through the members of a C++ struct?

I want to step through the members of a C++ struct and print out their values. I can easily code this explicitly, but is there any way of doing it without actually knowing what's in the struct?
I suppose I'm looking for a C++ equivalent of C#'s foreach command.
Thanks for any help.
ADD: I'm doing something like this in C#. This code sets the struct members from an XML file read previously:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct SettingsStruct
{
public uint nLength;
}
private void UpdateSettings()
{
SettingsStruct settings = new SettingsStruct();
foreach (FieldInfo fieldInfo in typeof(SettingsStruct).GetFields())
{
string settingName = "SETTING." + fieldInfo.Name.ToUpper();
if (appSettings.Contains(settingName))
{
switch (fieldInfo.FieldType.FullName)
{
case "System.UInt32":
fieldInfo.SetValueDirect(__makeref(settings), uint.Parse((string)appSettings[settingName]));
break;
}
}
}
}
If you are willing to use boost fusion you can do this. First "promote" this structure to a fusion sequence, and then you can iterate through the sequence printing out each member.
You could overload operator<< for your struct, then you only have to write the code once.
The following Stackoverflow answer should give you an idea on what you are looking for
Iterate Over Struct; Easily Display Struct Fields And Values In a RichEdit Box
Afraid not. C++ offers limited reflective capability. The RTTI C++ system gives you access to types, but no introspection to the fields within that type.
With some macro wizardry / hackery you might be able to achieve this, see Reflection for C++ for an example.
The foreach command does'nt do what you are saying in C#. The foreach iterates over the elements of a collection (array, set, list ...) not the members of a struct (say "length" ...).
The equivalent of foreach in C++ is to use iterators (xs.begin(), xs.end()). You can use BOOST_FOREACH to have a cleaner syntax (or for(X& s : xs) in C++1x).
C++ doesn't allow iteration over general class members. However, if you are prepared to accept some limitations, and use techniques that some will regard as pure evil, you can set up a framework to allow iteration over members of a particular family of class types. This works by abusing the fact that the default assignment operator is recursively applied to all members of a class.
First we need to declare the types to include in the iteration:
struct Visitable1;
struct Visitable2;
struct Visitable3;
We also need an abstract base class for operations to do while iterating (destructor omitted for brevity; for safety, it should be either virtual or protected):
struct Visitor
{
virtual void visit(Visitable1 &) = 0;
virtual void visit(Visitable2 &) = 0;
virtual void visit(Visitable3 &) = 0;
static Visitor * current;
};
and a base class (using the "curiously recursive template" idiom) for the types we can include in the iteration; this is where the operator abuse happens, modifying the behaviour of self-assignment:
template <typename T>
struct Visitable
{
void operator=(Visitable const & other)
{
if (&other == this) {
Visitor::current->visit(static_cast<T&>(*this));
}
}
};
struct Visitable1 : Visitable<Visitable1> { /* some stuff */ };
struct Visitable2 : Visitable<Visitable2> { /* some stuff */ };
struct Visitable3 : Visitable<Visitable3> { /* some stuff */ };
Finally, we can define the iteration itself:
template <class T, class Visitor>
void for_each(T & t, Visitor v)
{
Visitor::current = &v;
t = t;
}
This does have some notable shortcomings:
The "visit" functions are virtual, and so can't be generic. I can't currently think of a way to allow the use of different Visitor classes without an abstract base class. As a consequence, the iteration can only be applied to a predeclared set of types.
The use of a static variable (Visitor::current) means that only one iteration can be in progress at any time, giving thread-safety and reentrancy issues. I can't currently think of a better way to pass state to operator=, since this only works when overloading the default operator=, with a single argument of the same type as the assignee.
You may be lynched if anyone catches you writing code like this.
See codepad.org for a demonstration.

A property or indexer may not be passed as an out or ref parameter

I'm getting the above error and unable to resolve it.
I googled a bit but can't get rid of it.
Scenario:
I have class BudgetAllocate whose property is budget which is of double type.
In my dataAccessLayer,
In one of my classes I am trying to do this:
double.TryParse(objReader[i].ToString(), out bd.Budget);
Which is throwing this error:
Property or indexer may not be passed as an out or ref parameter at
compile time.
I even tried this:
double.TryParse(objReader[i].ToString().Equals(DBNull.Value) ? "" : objReader[i].ToString(), out bd.Budget);
Everything else is working fine and references between layers are present.
Others have given you the solution, but as to why this is necessary: a property is just syntactic sugar for a method.
For example, when you declare a property called Name with a getter and setter, under the hood the compiler actually generates methods called get_Name() and set_Name(value). Then, when you read from and write to this property, the compiler translates these operations into calls to those generated methods.
When you consider this, it becomes obvious why you can't pass a property as an output parameter - you would actually be passing a reference to a method, rather than a reference to an object a variable, which is what an output parameter expects.
A similar case exists for indexers.
This is a case of a leaky abstraction. A property is actually a method, the get and set accessors for an indexer get compiled to get_Index() and set_Index methods. The compiler does a terrific job hiding that fact, it automatically translates an assignment to a property to the corresponding set_Xxx() method for example.
But this goes belly up when you pass a method parameter by reference. That requires the JIT compiler to pass a pointer to the memory location of the passed argument. Problem is, there isn't one, assigning the value of a property requires calling the setter method. The called method cannot tell the difference between a passed variable vs a passed property and can thus not know whether a method call is required.
Notable is that this actually works in VB.NET. For example:
Class Example
Public Property Prop As Integer
Public Sub Test(ByRef arg As Integer)
arg = 42
End Sub
Public Sub Run()
Test(Prop) '' No problem
End Sub
End Class
The VB.NET compiler solves this by automatically generating this code for the Run method, expressed in C#:
int temp = Prop;
Test(ref temp);
Prop = temp;
Which is the workaround you can use as well. Not quite sure why the C# team didn't use the same approach. Possibly because they didn't want to hide the potentially expensive getter and setter calls. Or the completely undiagnosable behavior you'll get when the setter has side-effects that change the property value, they'll disappear after the assignment. Classic difference between C# and VB.NET, C# is "no surprises", VB.NET is "make it work if you can".
you cannot use
double.TryParse(objReader[i].ToString(), out bd.Budget);
replace bd.Budget with some variable.
double k;
double.TryParse(objReader[i].ToString(), out k);
Possibly of interest - you could write your own:
//double.TryParse(, out bd.Budget);
bool result = TryParse(s, value => bd.Budget = value);
}
public bool TryParse(string s, Action<double> setValue)
{
double value;
var result = double.TryParse(s, out value);
if (result) setValue(value);
return result;
}
Place the out parameter into a local variable and then set the variable into bd.Budget:
double tempVar = 0.0;
if (double.TryParse(objReader[i].ToString(), out tempVar))
{
bd.Budget = tempVar;
}
Update: Straight from MSDN:
Properties are not variables and
therefore cannot be passed as out
parameters.
This is a very old post, but I'm ammending the accepted, because there is an even more convienient way of doing this which I didn't know.
It's called inline declaration and might have always been available (as in using statements) or it might have been added with C#6.0 or C#7.0 for such cases, not sure, but works like a charm anyway:
Inetad of this
double temp;
double.TryParse(objReader[i].ToString(), out temp);
bd.Budget = temp;
use this:
double.TryParse(objReader[i].ToString(), out double temp);
bd.Budget = temp;
So Budget is a property, correct?
Rather first set it to a local variable, and then set the property value to that.
double t = 0;
double.TryParse(objReader[i].ToString(), out t);
bd.Budget = t;
Usually when I'm trying to do this it's because I want to set my property or leave it at the default value. With the help of this answer and dynamic types we can easily create a string extension method to keep it one lined and simple.
public static dynamic ParseAny(this string text, Type type)
{
var converter = TypeDescriptor.GetConverter(type);
if (converter != null && converter.IsValid(text))
return converter.ConvertFromString(text);
else
return Activator.CreateInstance(type);
}
Use like so;
bd.Budget = objReader[i].ToString().ParseAny(typeof(double));
// Examples
int intTest = "1234".ParseAny(typeof(int)); // Result: 1234
double doubleTest = "12.34".ParseAny(typeof(double)); // Result: 12.34
decimal pass = "12.34".ParseAny(typeof(decimal)); // Result: 12.34
decimal fail = "abc".ParseAny(typeof(decimal)); // Result: 0
string nullStr = null;
decimal failedNull = nullStr.ParseAny(typeof(decimal)); // Result: 0
Optional
On a side note, if that's an SQLDataReader you may also make use of GetSafeString extension(s) to avoid null exceptions from the reader.
public static string GetSafeString(this SqlDataReader reader, int colIndex)
{
if (!reader.IsDBNull(colIndex))
return reader.GetString(colIndex);
return string.Empty;
}
public static string GetSafeString(this SqlDataReader reader, string colName)
{
int colIndex = reader.GetOrdinal(colName);
if (!reader.IsDBNull(colIndex))
return reader.GetString(colIndex);
return string.Empty;
}
Use like so;
bd.Budget = objReader.GetSafeString(i).ParseAny(typeof(double));
bd.Budget = objReader.GetSafeString("ColumnName").ParseAny(typeof(double));
I had the same problem (5 minutes ago) and I solved it using old style properties with getter and setter, whose use variables.
My code:
public List<int> bigField = new List<int>();
public List<int> BigField { get { return bigField; } set { bigField = value; } }
So, I just used bigField variable. I'm not the programmer, if I misunderstood the question, I'm really sorry.

What are your favorite little used C# trick? [duplicate]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
This came to my mind after I learned the following from this question:
where T : struct
We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.
Some of us even mastered the stuff like Generics, anonymous types, lambdas, LINQ, ...
But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?
Here are the revealed features so far:
Keywords
yield by Michael Stum
var by Michael Stum
using() statement by kokos
readonly by kokos
as by Mike Stone
as / is by Ed Swangren
as / is (improved) by Rocketpants
default by deathofrats
global:: by pzycoman
using() blocks by AlexCuse
volatile by Jakub Šturc
extern alias by Jakub Šturc
Attributes
DefaultValueAttribute by Michael Stum
ObsoleteAttribute by DannySmurf
DebuggerDisplayAttribute by Stu
DebuggerBrowsable and DebuggerStepThrough by bdukes
ThreadStaticAttribute by marxidad
FlagsAttribute by Martin Clarke
ConditionalAttribute by AndrewBurns
Syntax
?? (coalesce nulls) operator by kokos
Number flaggings by Nick Berardi
where T:new by Lars Mæhlum
Implicit generics by Keith
One-parameter lambdas by Keith
Auto properties by Keith
Namespace aliases by Keith
Verbatim string literals with # by Patrick
enum values by lfoust
#variablenames by marxidad
event operators by marxidad
Format string brackets by Portman
Property accessor accessibility modifiers by xanadont
Conditional (ternary) operator (?:) by JasonS
checked and unchecked operators by Binoj Antony
implicit and explicit operators by Flory
Language Features
Nullable types by Brad Barker
Anonymous types by Keith
__makeref __reftype __refvalue by Judah Himango
Object initializers by lomaxx
Format strings by David in Dakota
Extension Methods by marxidad
partial methods by Jon Erickson
Preprocessor directives by John Asbeck
DEBUG pre-processor directive by Robert Durgin
Operator overloading by SefBkn
Type inferrence by chakrit
Boolean operators taken to next level by Rob Gough
Pass value-type variable as interface without boxing by Roman Boiko
Programmatically determine declared variable type by Roman Boiko
Static Constructors by Chris
Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacid
__arglist by Zac Bowling
Visual Studio Features
Select block of text in editor by Himadri
Snippets by DannySmurf
Framework
TransactionScope by KiwiBastard
DependantTransaction by KiwiBastard
Nullable<T> by IainMH
Mutex by Diago
System.IO.Path by ageektrapped
WeakReference by Juan Manuel
Methods and Properties
String.IsNullOrEmpty() method by KiwiBastard
List.ForEach() method by KiwiBastard
BeginInvoke(), EndInvoke() methods by Will Dean
Nullable<T>.HasValue and Nullable<T>.Value properties by Rismo
GetValueOrDefault method by John Sheehan
Tips & Tricks
Nice method for event handlers by Andreas H.R. Nilsson
Uppercase comparisons by John
Access anonymous types without reflection by dp
A quick way to lazily instantiate collection properties by Will
JavaScript-like anonymous inline-functions by roosteronacid
Other
netmodules by kokos
LINQBridge by Duncan Smart
Parallel Extensions by Joel Coehoorn
This isn't C# per se, but I haven't seen anyone who really uses System.IO.Path.Combine() to the extent that they should. In fact, the whole Path class is really useful, but no one uses it!
I'm willing to bet that every production app has the following code, even though it shouldn't:
string path = dir + "\\" + fileName;
lambdas and type inference are underrated. Lambdas can have multiple statements and they double as a compatible delegate object automatically (just make sure the signature match) as in:
Console.CancelKeyPress +=
(sender, e) => {
Console.WriteLine("CTRL+C detected!\n");
e.Cancel = true;
};
Note that I don't have a new CancellationEventHandler nor do I have to specify types of sender and e, they're inferable from the event. Which is why this is less cumbersome to writing the whole delegate (blah blah) which also requires you to specify types of parameters.
Lambdas don't need to return anything and type inference is extremely powerful in context like this.
And BTW, you can always return Lambdas that make Lambdas in the functional programming sense. For example, here's a lambda that makes a lambda that handles a Button.Click event:
Func<int, int, EventHandler> makeHandler =
(dx, dy) => (sender, e) => {
var btn = (Button) sender;
btn.Top += dy;
btn.Left += dx;
};
btnUp.Click += makeHandler(0, -1);
btnDown.Click += makeHandler(0, 1);
btnLeft.Click += makeHandler(-1, 0);
btnRight.Click += makeHandler(1, 0);
Note the chaining: (dx, dy) => (sender, e) =>
Now that's why I'm happy to have taken the functional programming class :-)
Other than the pointers in C, I think it's the other fundamental thing you should learn :-)
From Rick Strahl:
You can chain the ?? operator so that you can do a bunch of null comparisons.
string result = value1 ?? value2 ?? value3 ?? String.Empty;
Aliased generics:
using ASimpleName = Dictionary<string, Dictionary<string, List<string>>>;
It allows you to use ASimpleName, instead of Dictionary<string, Dictionary<string, List<string>>>.
Use it when you would use the same generic big long complex thing in a lot of places.
From CLR via C#:
When normalizing strings, it is highly
recommended that you use
ToUpperInvariant instead of
ToLowerInvariant because Microsoft has
optimized the code for performing
uppercase comparisons.
I remember one time my coworker always changed strings to uppercase before comparing. I've always wondered why he does that because I feel it's more "natural" to convert to lowercase first. After reading the book now I know why.
My favorite trick is using the null coalesce operator and parentheses to automagically instantiate collections for me.
private IList<Foo> _foo;
public IList<Foo> ListOfFoo
{ get { return _foo ?? (_foo = new List<Foo>()); } }
Avoid checking for null event handlers
Adding an empty delegate to events at declaration, suppressing the need to always check the event for null before calling it is awesome. Example:
public delegate void MyClickHandler(object sender, string myValue);
public event MyClickHandler Click = delegate {}; // add empty delegate!
Let you do this
public void DoSomething()
{
Click(this, "foo");
}
Instead of this
public void DoSomething()
{
// Unnecessary!
MyClickHandler click = Click;
if (click != null) // Unnecessary!
{
click(this, "foo");
}
}
Please also see this related discussion and this blog post by Eric Lippert on this topic (and possible downsides).
Everything else, plus
1) implicit generics (why only on methods and not on classes?)
void GenericMethod<T>( T input ) { ... }
//Infer type, so
GenericMethod<int>(23); //You don't need the <>.
GenericMethod(23); //Is enough.
2) simple lambdas with one parameter:
x => x.ToString() //simplify so many calls
3) anonymous types and initialisers:
//Duck-typed: works with any .Add method.
var colours = new Dictionary<string, string> {
{ "red", "#ff0000" },
{ "green", "#00ff00" },
{ "blue", "#0000ff" }
};
int[] arrayOfInt = { 1, 2, 3, 4, 5 };
Another one:
4) Auto properties can have different scopes:
public int MyId { get; private set; }
Thanks #pzycoman for reminding me:
5) Namespace aliases (not that you're likely to need this particular distinction):
using web = System.Web.UI.WebControls;
using win = System.Windows.Forms;
web::Control aWebControl = new web::Control();
win::Control aFormControl = new win::Control();
I didn't know the "as" keyword for quite a while.
MyClass myObject = (MyClass) obj;
vs
MyClass myObject = obj as MyClass;
The second will return null if obj isn't a MyClass, rather than throw a class cast exception.
Two things I like are Automatic properties so you can collapse your code down even further:
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
becomes
public string Name { get; set;}
Also object initializers:
Employee emp = new Employee();
emp.Name = "John Smith";
emp.StartDate = DateTime.Now();
becomes
Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()}
The 'default' keyword in generic types:
T t = default(T);
results in a 'null' if T is a reference type, and 0 if it is an int, false if it is a boolean,
etcetera.
Attributes in general, but most of all DebuggerDisplay. Saves you years.
The # tells the compiler to ignore any
escape characters in a string.
Just wanted to clarify this one... it doesn't tell it to ignore the escape characters, it actually tells the compiler to interpret the string as a literal.
If you have
string s = #"cat
dog
fish"
it will actually print out as (note that it even includes the whitespace used for indentation):
cat
dog
fish
I think one of the most under-appreciated and lesser-known features of C# (.NET 3.5) are Expression Trees, especially when combined with Generics and Lambdas. This is an approach to API creation that newer libraries like NInject and Moq are using.
For example, let's say that I want to register a method with an API and that API needs to get the method name
Given this class:
public class MyClass
{
public void SomeMethod() { /* Do Something */ }
}
Before, it was very common to see developers do this with strings and types (or something else largely string-based):
RegisterMethod(typeof(MyClass), "SomeMethod");
Well, that sucks because of the lack of strong-typing. What if I rename "SomeMethod"? Now, in 3.5 however, I can do this in a strongly-typed fashion:
RegisterMethod<MyClass>(cl => cl.SomeMethod());
In which the RegisterMethod class uses Expression<Action<T>> like this:
void RegisterMethod<T>(Expression<Action<T>> action) where T : class
{
var expression = (action.Body as MethodCallExpression);
if (expression != null)
{
// TODO: Register method
Console.WriteLine(expression.Method.Name);
}
}
This is one big reason that I'm in love with Lambdas and Expression Trees right now.
"yield" would come to my mind. Some of the attributes like [DefaultValue()] are also among my favorites.
The "var" keyword is a bit more known, but that you can use it in .NET 2.0 applications as well (as long as you use the .NET 3.5 compiler and set it to output 2.0 code) does not seem to be known very well.
Edit: kokos, thanks for pointing out the ?? operator, that's indeed really useful. Since it's a bit hard to google for it (as ?? is just ignored), here is the MSDN documentation page for that operator: ?? Operator (C# Reference)
I tend to find that most C# developers don't know about 'nullable' types. Basically, primitives that can have a null value.
double? num1 = null;
double num2 = num1 ?? -100;
Set a nullable double, num1, to null, then set a regular double, num2, to num1 or -100 if num1 was null.
http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx
one more thing about Nullable type:
DateTime? tmp = new DateTime();
tmp = null;
return tmp.ToString();
it is return String.Empty. Check this link for more details
Here are some interesting hidden C# features, in the form of undocumented C# keywords:
__makeref
__reftype
__refvalue
__arglist
These are undocumented C# keywords (even Visual Studio recognizes them!) that were added to for a more efficient boxing/unboxing prior to generics. They work in coordination with the System.TypedReference struct.
There's also __arglist, which is used for variable length parameter lists.
One thing folks don't know much about is System.WeakReference -- a very useful class that keeps track of an object but still allows the garbage collector to collect it.
The most useful "hidden" feature would be the yield return keyword. It's not really hidden, but a lot of folks don't know about it. LINQ is built atop this; it allows for delay-executed queries by generating a state machine under the hood. Raymond Chen recently posted about the internal, gritty details.
Unions (the C++ shared memory kind) in pure, safe C#
Without resorting to unsafe mode and pointers, you can have class members share memory space in a class/struct. Given the following class:
[StructLayout(LayoutKind.Explicit)]
public class A
{
[FieldOffset(0)]
public byte One;
[FieldOffset(1)]
public byte Two;
[FieldOffset(2)]
public byte Three;
[FieldOffset(3)]
public byte Four;
[FieldOffset(0)]
public int Int32;
}
You can modify the values of the byte fields by manipulating the Int32 field and vice-versa. For example, this program:
static void Main(string[] args)
{
A a = new A { Int32 = int.MaxValue };
Console.WriteLine(a.Int32);
Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", a.One, a.Two, a.Three, a.Four);
a.Four = 0;
a.Three = 0;
Console.WriteLine(a.Int32);
}
Outputs this:
2147483647
FF FF FF 7F
65535
just add
using System.Runtime.InteropServices;
Using # for variable names that are keywords.
var #object = new object();
var #string = "";
var #if = IpsoFacto();
If you want to exit your program without calling any finally blocks or finalizers use FailFast:
Environment.FailFast()
Returning anonymous types from a method and accessing members without reflection.
// Useful? probably not.
private void foo()
{
var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });
Console.WriteLine("Name: {0} Badges: {1}", user.Name, user.Badges);
}
object GetUserTuple()
{
return new { Name = "dp", Badges = 5 };
}
// Using the magic of Type Inference...
static T AnonCast<T>(object obj, T t)
{
return (T) obj;
}
Here's a useful one for regular expressions and file paths:
"c:\\program files\\oldway"
#"c:\program file\newway"
The # tells the compiler to ignore any escape characters in a string.
Mixins. Basically, if you want to add a feature to several classes, but cannot use one base class for all of them, get each class to implement an interface (with no members). Then, write an extension method for the interface, i.e.
public static DeepCopy(this IPrototype p) { ... }
Of course, some clarity is sacrificed. But it works!
Not sure why anyone would ever want to use Nullable<bool> though. :-)
True, False, FileNotFound?
This one is not "hidden" so much as it is misnamed.
A lot of attention is paid to the algorithms "map", "reduce", and "filter". What most people don't realize is that .NET 3.5 added all three of these algorithms, but it gave them very SQL-ish names, based on the fact that they're part of LINQ.
"map" => Select Transforms data
from one form into another
"reduce" => Aggregate Aggregates
values into a single result
"filter" => Where Filters data
based on a criteria
The ability to use LINQ to do inline work on collections that used to take iteration and conditionals can be incredibly valuable. It's worth learning how all the LINQ extension methods can help make your code much more compact and maintainable.
Environment.NewLine
for system independent newlines.
If you're trying to use curly brackets inside a String.Format expression...
int foo = 3;
string bar = "blind mice";
String.Format("{{I am in brackets!}} {0} {1}", foo, bar);
//Outputs "{I am in brackets!} 3 blind mice"
?? - coalescing operator
using (statement / directive) - great keyword that can be used for more than just calling Dispose
readonly - should be used more
netmodules - too bad there's no support in Visual Studio
#Ed, I'm a bit reticent about posting this as it's little more than nitpicking. However, I would point out that in your code sample:
MyClass c;
if (obj is MyClass)
c = obj as MyClass
If you're going to use 'is', why follow it up with a safe cast using 'as'? If you've ascertained that obj is indeed MyClass, a bog-standard cast:
c = (MyClass)obj
...is never going to fail.
Similarly, you could just say:
MyClass c = obj as MyClass;
if(c != null)
{
...
}
I don't know enough about .NET's innards to be sure, but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one. It's hardly likely to break the processing bank either way; personally, I think the latter form looks cleaner too.
Maybe not an advanced technique, but one I see all the time that drives me crazy:
if (x == 1)
{
x = 2;
}
else
{
x = 3;
}
can be condensed to:
x = (x==1) ? 2 : 3;

Categories

Resources