Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Tuesday, 28 April 2009

Extension Methods in C# 3.0

A new function of C# 3.0 is Extension Methods.

"Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type."

For example, if you wanted a method to convert a temperature from celsius to fahrenheit, where previously you would use

int temp = 30;
int i = myClass.CelsiusToFahrenheit(temp);


using extension methods you can now use

int temp = 30;
int i = temp.CelsiusToFahrenheit();

To do this you would create a new static class to contain the static method CelsiusToFahrenheit. The key to extension methods is passing in the this keyword along with the variable. For example,


public static class myClass
{
public static int CelsiusToFahrenheit(this int temp)
{
return (9 / 5) * temp + 32;
}
}


This will now allow you to use the CelsiusToFahrenheit method on any integer variables.

You can also add methods to extend your own custom classes, and the methods can have different return types. For example, if you have your own class, TestClass, you can create a static method using extending TestClass, e.g.


public static DateTime doSomething(this TestClass t)
{
//do something
}


Which will then allow you to use:

TestClass t = new TestClass();
DateTime x = t.doSomething();

Sunday, 29 March 2009

Using keyword

When using anything that implements IDisposable (SqlDateReader, SqlConnection etc) you can use the using keyword to ensure that the object is disposed, e.g.

using (SqlDataReader reader = Dal.ExecuteReader(GetConnection(), "SelectProductAll"))
{
dsScrum.ProductTask.Clear();
if (reader.HasRows)
dsScrum.Product.Load(reader);
}



Is the same as:

SqlDataReader reader = Dal.ExecuteReader(GetConnection(),"SelectProductAll");
try
{
dsScrum.ProductTask.Clear();
if (reader.HasRows)
dsScrum.Product.Load(reader);
}
finally
{
if (reader != null)
reader.Dispose();
}

Thursday, 23 October 2008

& or && that is the question!

Using && instead of &.

if (phContent.Controls[0].ID == "ucSwJobs" & ((SWJobs)phContent.Controls[0]).CheckForCheckedJobs())
{
ShowMessage("You still have selected jobs in SW Jobs!");
}


If we used & in the above if statement we would get an error because the second evaluation relies on the first one being true. If we used && the first statement would fail and the second statement would throw an error.
By using a double && we stop the second statement being evealuated if the first fails!

Tuesday, 2 September 2008

Nullable Types

When using the System.Nullable syntax you can substitute it for T?

For example,

System.Nullable<int> intNullable; is the same as
int? intNullable;

If you have declared a non-nullable variable and are assigning it a value that could be null you can use the ?? syntax to give it a default value. For example:

int? intNullable = null;
int intNotNullable = intNullable ?? 99;

Would give the intNotNullable variable a value of 99 in the event of intNullable being null.

Thursday, 7 August 2008

Set a DateTimePicker to Blank

If you have ever had problems setting the text of a datetimepicker to blank (rather than the default value) then the following code example is the way to do it:

if (csMahService._EndDate.HasValue)
{
dtpEndDate.Value = csMahService._EndDate.Value;
}
else
{
dtpEndDate.CustomFormat = " ";
}

Note you have to set the Format property to Custom.

Monday, 14 July 2008

Edit and Continue debugging

With Edit and Continue for C#, you can make changes to your code in break mode while debugging. The changes can be applied without having to stop and restart the debugging session.

Edit and Continue is invoked automatically when you make changes in break mode, then choose a debugger execution command, such as Continue, Step, or Set Next Statement, or evaluate a function in a debugger window.

Note
Edit and Continue is not supported when debugging 64-bit code, the Compact Framework, optimized code, mixed native/managed code, or SQL CLR code. If you try to apply code changes in one of these scenarios, the debugger puts up a dialog box explaining that Edit and Continue is not supported.


To invoke Edit and Continue automatically
In break mode, make a change to your source code.

From the Debug menu, click Continue, Step, or Set Next Statement or evaluate a function in a debugger window.

The new code is compiled and the debugging continues with the new code. Some changes are not supported by Edit and Continue. For more information, see Supported Code Changes (C#).

To enable/disable Edit and Continue
On the Tools menu, click Options.

In the Options dialog box, expand the Debugging node, and select Edit and Continue.

In the Options dialog box Edit and Continue page, select or clear the Enable Edit and Continue check box.

The setting takes effect when you restart the debugging session.


Link

http://msdn.microsoft.com/en-us/library/ms164926(VS.80).aspx

Wednesday, 11 June 2008

Getting the current User Name in Windows programming

Use this for getting the user name when building a windows application in DotNet. Done!
--------------------------------------------------

//
Place this at the top, above your namespace declaration
using System.Security.Principal;


//In a specific event, place the following.
string a;
a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

Monday, 9 June 2008

Using TryParse() in C#

When we are validating integer input, usually from a textbox, we need to make sure that the text is a valid integer before we set the properties in our class.

We would normally have done this using the following type of code:

try
{
SomeInt = Convert.ToInt32(tbSomeInt.Text);
}
catch (Exception ex)
{
MessageBox.Show("Some int must be a valid integer");
return;
}

By using a try catch in this manner we add quite a bit of overhead to the work that the .Net framework has to do for us. We can use the TryParse() method to get round this.

int intSomeInt;
if (int.TryParse(tbSomeInt.Text, out intSomeInt) == true)
{
//if the conversion succeded
csSomeClass._SomeInt= intSomeInt;
}
else
{
MessageBox.Show("Some int must be a valid integer");
return;
}

This avoids the overhead of using the try and will run faster. Please note that you cannot use a class property in the out parameter of the method and must use a variable as above.

Here is a link to another blog that I found useful.
Free Hit Counter