• Advertisement
Sign in to follow this  

[.net] Useful/obscure .Net classes

This topic is 3976 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I've been tasked with a doing small learning session at work (less than 10 people, maybe 15 minutes). I was thinking that often times people may write code to perform tasks already covered by classes within the .Net framework. So I thought I'd present a few .Net classes that people may be not be aware of that might prove useful in their every day lives. I'd just present the basics of the class, what it does, some of its more useful methods, maybe some of its downfalls, and a small example. So does anyone have any suggestions? Examples of classes (or interfaces or whatever) that make your coding life easier in one way or another? They don't have to necessarily be obscure or necessarily the most absolutely useful thing in the world. Just something that people may not know about that might take some time and effort out of their work? Thanks!

Share this post


Link to post
Share on other sites
Advertisement
Depending on what kind of projects/How many people work o differet projects, you might want to present MSBuild and the accompanying classes.

There's also a whole slew of cool stuff in System.Diagnostics. Stuff like DebuggerDisplayAttribute can be useful if you end up debugging a given type a lot and looking for the same info often.

Share this post


Link to post
Share on other sites
Thanks Jfclavette. I'll look into System.Diagnostic and MSBuild. Any others to look into? I was thinking maybe System.Collections and doing a run-down of the advantages of different containers.

Share this post


Link to post
Share on other sites
I find that a lot of programmers aren't aware/proficient at using .Net Serialization and often recreate their own serialization framework.

Share this post


Link to post
Share on other sites
I would avoid System.Collections and instead work on System.Collections.Generics. The generic collection classes are much neater and more type safe (and if you do need to have a variable type container, you can always explicitly use Object).

If they have used C/C++ a lot, then this construct would be familiar:

enum AnEnum
{
Item1,
Item2
};

const char *const AnEnumNames [] =
{
"Item1",
"Item2"
};

which you'd use a lot for loading/saving data. In .Net (this is the C++/CLI version):

enum class AnEnum
{
Item1,
Item2
};

for each (String ^item_name in Enum::GetNames (AnEnum::typeid))
{
// item name is the string form of the enum value
}

AnEmum enum_value = AnEnum::Item2;
String ^enum_value_name = enum_value.ToString ();

And finally with enums, don't forget the FlagsAttribute specifier for enums.

Don't use the form designer in DevStudio - it produces horrible code, especially with C++/CLI source. It also doesn't support localisation. And it's in code which requires a recompile to make changes. Consider building a XAML type system, i.e. a data driven framework for form design.

Can't think of anything else off the top of my head.

Skizz

Share this post


Link to post
Share on other sites
Quote:
Original post by benryves
System.CodeDom and System.CodeDom.Compiler can be used to parse source files and compile them into assemblies - couple this with System.Reflection to load the output and you can create scriptable applications quite easily.


Not forgetting of course to ensure the source of the script is trusted, i.e. it hasn't been sent to your web server from a HTTP POST request.

Skizz

Share this post


Link to post
Share on other sites
I (with a bit of direction stumbled across the Dictionary and found it to be quite useful. I also second intrest86's suggestion of serialization.

Share this post


Link to post
Share on other sites
System.Collections.ObjectModel has useful base classes if you want to expose a collection from a class. Some of the classes let you receive notifications of collection changes, and there are read-only collections as well.

Share this post


Link to post
Share on other sites
You might want to go into some of the neat tricks you can do with reflection if they're people coming from C/C++. For me it was the kind of thing I would never, ever use unless some one showed me what it could do since the whole concept doesn't make any sense to a C/C++ programmer.

I also have fun writing sloppy code all over the place with anonymous delegates. Making a whole new method is just so tiresome sometimes.

Share this post


Link to post
Share on other sites
Some of these are hints and tricks.. but still good to know :-)


Not a class but syntax:


have you ever done this?

if (myString != null)
return myString;
else
return "Empty";

well.. how about:

return myString ?? "Empty";

Both are equivalent [wink]



System.BitConverter and System.Buffer are very useful for bit/byte manipulation.



Need memcpy? Marshal.Copy().



A lot of operators work on integers by default, ie 1 << 15 will be integer. However so will 1 << 42. This will actually be the same as 1 << 10. However 1L << 42 will be fine. Bytes always get converted to integer when doing bitwise operations on them.



unchecked and checked blocks:

checked
{
byte b = 255;
b++; // exception, overflow
}

can also be used in an equation:

int z = checked(b+100);


There is a very subtle issue with floating point byte conversions.
If you have a float array, and want to manually set a value in that array (as 4 bytes) - eg, you are dumping byte RGBA colours into a float array..
BitConverter.ToSingle() won't work... In the event the bytes are X Y Z 255, the resulting float is NaN, which automatically gets converted to X Y 240 255 (iirc). The way to get around it is by using Buffer.BlockCopy() to copy an array with the 4 bytes into the float array. This one took a while to track down.



For threading, AutoResetEvents and ManualResetEvents are awesome.
As are ReadWriteLocks.
If you have a large number of tasks running, and you want to react when one finishes, you can do:

WaitHandle[] handles = {threadOneCompletedTaskEvent,threadTwoCom.... };

while (tasksToDo)
threads[WaitHandle.WaitAny(handles)].AssignNextTask(...);

Each handle will be an AutoResetEvent in this case.
There will be another autoreset event that signals the worker to start up again (set in AssignNextTask). Use WaitHandle.SignalAndWait(..,..); when a task finishs.


Never have ushort,ubyte,uint or ulong as parametres for public methods. Unless:
you have them as an overload with the following attribute:
[CLSCompliant(false)]



Self managed events...
What may not be obvious is that a Property can be an event too... This is *really* useful for roll-your-own events.

public event MyEventHandler MyEvent
{
add {}
remove {}
}



AppDomain.CurrentDomain has some very useful events.

such as:

AppDomain.CurrentDomain.AssemblyResolve
If .net can't find an assembly you reference, it will call this event (instead of crashing). You can load it manually with Assembly.Load() here if you want (say, from a .zip file - to keep your app nice and small)

AppDomain.CurrentDomain.UnhandledException
Should be obvious :-) - although use it as a last resort



Assembly.Load(byte[]) does not correctly load assembly evidence, however Assembly.ReflectionOnlyLoad(byte[]) does. So you can call Assembly.ReflectionOnlyLoad, then use the evidence in Assembly.Load(byte[],assembly.Evidence,...)




Sometimes, you want to scan all the .dll files your application has, and find all classes implementing an interface (or class, etc). Eg you might have an editor, and it wants to know what entities it can let you add.
Here is how to do it:

Store the interface/class that you want to scan for in it's own assembly.

This should probably be *recursive*


foreach (AssemblyName an in current_assembly.GetReferencedAssemblies())
{
Assembly assembly = Assembly.ReflectionOnlyLoad(an.FullName);

if (assembly.GetReferencedAssemblies().Contains(interface_assembly_name))
{
assembly = Assembly.Load(an.FullName);
foreach (Type t in assembly.GetExportedTypes())
{
if (interface_type.IsAssignableFrom(t))
types.Add(t);
}
}
}


This will be *MUCH* faster than loading every .dll in the directory, or similar operations.




When using XML classes, eg XmlElement, do not use SelectNodes() or SelectSingleNode(), as these use xpath (I think). Use GetElementsByTagName().



Want to confuse someone? Have a Queue filled with delegates:

if (taskQueue.Count > 0)
taskQueue.Dequeue()();



System.Array has loads of useful static methods. Such as Array.Resize() [wink]


System.Activator can be used to create objects from a type. You can also do this by using reflection to get the ConstructorInfo of a Constructor on a type.
This can even be done for remote objects over the web.


System.Environment contains loads of stuff.




there are of course loads and loads more. I'm just browsing some of my code and picking out interesting things.

[Edited by - RipTorn on March 25, 2007 11:42:10 AM]

Share this post


Link to post
Share on other sites
Quote:
Original post by RipTorn
return myString ?? "Empty";


Wow! I've read the whole spec, tons of tutorials etc, but I've missed that one!! thanks a lot!!

Share this post


Link to post
Share on other sites
That SecureString is nice to know. System.Environment and the stuff in Diagnostics (like StackTrace) is useful. XML, serialization, threading and network are useful but not terribly obscure.

StringBuilder is good to know and subtle in its benefits.

Generic delegates are fairly useful in cutting down cookie cutter typing.

implicit coversion operators help cut down typing a bit with functors:


class SomeEventTosser{
public delegate void EventType(SomeEventTosser src);
public event EventType OnEvent;
}

class SomeEventFunctor{
// params
public void MainMethod(){
// use params to handle incoming event.
}

public static implicit operator SomeEventTosser.EventType( SomeEventFunctor rhs){
return( rhs.MainMethod );
}
}

// Allows:
SomeEventTosser foo = new SomeEventTosser();

foo.OnEvent += new SomeEventFunctor( /* params */ );




Allows for a little more curt syntax while still being pretty descriptive. And remember even being subscribed to an event will keep an object alive, so in the above scenario the functor still stick around as long as the event does.

Share this post


Link to post
Share on other sites
Some very interesting stuff in this thread!

System.Reflection is great, although it can get a bit slow if you go overboard on it. Hashtables are also very useful, and I second the nomination of the StringBuilder too.

Share this post


Link to post
Share on other sites
Indeed, thank you to everyone for your suggestions. I've learned a ton too just reading the thread, let alone the stuff I've since MSDN'd.

Share this post


Link to post
Share on other sites
Quote:
Original post by RipTorn


have you ever done this?

if (myString != null)
return myString;
else
return "Empty";

well.. how about:

return myString ?? "Empty";

Both are equivalent [wink]



I've never seen double ? syntax before, I'll have to look that one up. However, I guess from my C++ days I never use the first example, I always use tri state if, as well as using the built in Empty string:

return myString != null ? myString : string.Empty;

Another one I just found that is slightly different but very useful is:

bool string.IsNullOrEmpty(string value);


Share this post


Link to post
Share on other sites
You can 'foreach' through enums without having a "maximum" entry in the enum:


enum MyEnum
{
A, B, C
}

void SomeFunc()
{
MyEnum[] values = (MyEnum[])Enum.GetValues(MyEnum);

foreach (MyEnum foo in values)
{
// stuff here.
}
}

Share this post


Link to post
Share on other sites
http://www.codeplex.com/entlib

While not in the framework, Microsoft has a nice set of development libraries called Enterprise Library. It has a lot of functionality that people often write their own code for.

It's composed of 'blocks' for logging, exception handling, caching, security, data access, and others. Each of these blocks uses a separate section in app.config and can easily plug in to an existing system. A config editor is also supplied.

The Composite UI Block (CAB) provides much of the infrastructure for developing enterprise-scale applications. A Smart Client Software Factory (SCSF) package automates many CAB tasks such as generating code files and setting up VS projects. For small projects this is totally unnecessary.

A new version is due out at the beginning of April with a couple new blocks.

Share this post


Link to post
Share on other sites
Maybe the RegEx class is too obvious but judging by the amount of code I see that has dozens of lines of manual string parsing code to do something that would be a simple regular expression it seems there's still a lot of programmers out there who aren't familiar with regular expressions.

MSBuild (and the associated framework classes) is definitely worth looking into for any build scripting tasks, it's quite powerful, though the syntax of the project files can be a little cryptic.

Share this post


Link to post
Share on other sites
Tip 1: If you want to render your own controls, System.Windows.Forms.Visualstyles contains classes to render using the applied visual style (i.e. Luna, Aero). My custom buttons were looking ancient until I discovered it.

Tip 2: VS 2005 lets you define application settings and will automatically generate code to read/write settings and access them programatically (new projects get a Settings.settings file under the Properties subfolder). The Type of the setting has a list of commonly used types. Clicking "Browse" on that list presents a tree with a lot more types from the BCL, but none from your project.

Now the tip: You can use a type from your project by specifying its full name in the "Selected type" edit box. There's a bug where doing so will add a self-reference to your project, but just delete that new reference and everything works.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement