Alright, so I'll admit to having been a VB for most of my career because I just find it more intuitive. Recently, though, I have been expanding my horizons and "c#-pening" my .Net skills. Tonight I cam across a really cool C# feature called verbatim string literals. Instead of having to escape certain special characters in a string literal such as in a file path:
string path = "c:\\c#.net\\file
You can simply prefix your literal with an @ symbol and everything between the quotes is taken literally by the c# compiler
string path = @"c:\c#.net\files";
The one caveat is that to use quotes around a character in a verbatim string literal you have to code the literal with double quotes like:
string msg = @"Type ""x"" to exit";
So, you do have to escape some characters but whattya want?
BTW - the examples were taken from Murach's C# 2008. I don't even know the guy but Mike Murach has taught me abotu 3 different programming languages (including SQL Server that isn't really a programming language, technically).
Tuesday, August 4, 2009
Sunday, August 2, 2009
C# Extension Methods - You don't like my methods? Add yer' own.
Have you ever scoured the methods of the string class looking for that method that know has to be there? I do this all the time. I used to write inline functions to handle this until I got smarter and figured out how to create a seperate class of static "helper" methods. This made coding a little easier but now in the .Net 3.5 and .Net 4.0 Framework the new Extension methods have hit the scene. Now, when you're scouring intellisense for that perfect string method and you don't find it, just add it yourself and without subclassing!
Extension methods are static methods that are called as if they were public members of the original class. In other words, your extension method will show up in Intellisense.
To use this method, simply call it...
Extension methods are static methods that are called as if they were public members of the original class. In other words, your extension method will show up in Intellisense.
namespace ExtensionMethods
{
public static class MyExtensions
{
public static bool WordSaysDog(this String str)
{
If (str == "dog"){
return true;
}
else{
return false;
}
}
}
}
To use this method, simply call it...
string s = "Dog";
bool isDog = s.WordSaysDog();
Subscribe to:
Comments (Atom)