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

Tuesday, August 16, 2011

Type Inference

To understand type inference, let us look at couple of lines of code.

var count = 1;
var output = "This is a string";
var employees = new EmployeesCollection();

In the above lines of code, the compiler sees the var keyword, looks at the assignment to count, and determines that it should be an Int32, then assigns 1 to it. When it sees that you assign a string to the output variable, it determines that output should be of type System.String. Same goes for employees collection object. As you would have guessed by now, var is a new keyword introduced in C# 3.0 that has a special meaning. var is used to signal the compiler that you are using the new Local Variable Type Inference feature in C# 3.0.

As an example, let us modify our string query example to use the var keyword.




string[] names = {"John", "Peter", "Joe", "Patrick", "Donald", "Eric"};
var namesWithFiveCharacters =
from name in names
where name.Length < 5
select name'
var lstResults = new List();
foreach(var name in namesWithFiveCharacters)
lstResults.Add(name);



As the above code shows, the variable namesWithFiveCharacters now uses the type "var" instead of IEnumerable. Using "var" is much more extensible since it tells the compiler to infer the type from the assignment. In this case, based on the results of the query, which is IEnumerable, the compiler will automatically assume that it is a variable of type IEnumerable.

If you run the code, it still produces the same output.
(http://www.15seconds.com/issue/060713.htm)

Wednesday, January 28, 2009

StringComparison

Here is a great article on when to use the StringComparison.

http://msdn.microsoft.com/en-us/library/ms973919.aspx

DO: Use StringComparison.Ordinal or OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.

DO: Use StringComparison.Ordinal and OrdinalIgnoreCase comparisons for increased speed.

DO: Use StringComparison.CurrentCulture-based string operations when displaying the output to the user.

DO: Switch current use of string operations based on the invariant culture to use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase when the comparison is linguistically irrelevant (symbolic, for example).

DO: Use ToUpperInvariant rather than ToLowerInvariant when normalizing strings for comparison.

DON'T: Use overloads for string operations that don't explicitly or implicitly specify the string comparison mechanism.

DON'T: Use StringComparison.InvariantCulture-based string operations in most cases; one of the few exceptions would be persisting linguistically meaningful but culturally-agnostic data.

Thursday, January 22, 2009

Use delegate to sort the generic list (collection)

Here is an example of how to use the delegate to sort the list:

returnList.Sort(delegate(IMyClass x, IMyClass y)
{
return String.Compare(x.Name, y.Name);
});

So, instead of override the ICompare, you can use this short-cut to return a sorted list.

Here is how to just make your Thing class implement IComparable, implementing the CompareTo method like this:

public int CompareTo(Thing other)
{
return Name.CompareTo(other.Name);
}

Tuesday, December 02, 2008

Validate image size, type, and dimension

When upload images to file server or database, most likely we'll put some restrictions on the size, dimensions, and type of image.

In my asp.net project, I used the custom validator to accomplish this goal. In the validator function, we can check the size, dimension, and type. Make sure to use Page.IsValid in order to show the error messages.

    protected void valImage_ServerValidate(object source, ServerValidateEventArgs args)
{
int maxSize = 1024 * 1024;
int maxWidth = 350;
int maxHeight = 225;

if (args.IsValid)
{
if (FileUploadImage.PostedFile.ContentLength > maxSize)
{
args.IsValid = false;
CustomValidatorFile.ErrorMessage = "The image file size must be less than 1 MB.";
}
else if (FileUploadImage.PostedFile.ContentType != "image/jpeg" &&
FileUploadImage.PostedFile.ContentType != "image/pjpeg")
{
args.IsValid = false;
CustomValidatorFile.ErrorMessage = "The image file type must be jpeg.";
}
else
{
GetNewImage(); //put image stream in the session state;
using (Bitmap bitmap = new Bitmap(FileUploadImage.PostedFile.InputStream, false))
{
if (bitmap.Width > maxWidth || bitmap.Height > maxHeight)
{
args.IsValid = false;
CustomValidatorFile.ErrorMessage = "The image dimension must be less than 225px in height and 300px in width.";
}
}
}
}
}


reference: http://aspalliance.com/781_CodeSnip_Validate_Image_Size_Dimension_and_Type_Uploads;
http://www.mikeborozdin.com/post/ASPNET-Image-Uploading-(part-I).aspx

Friday, May 02, 2008

Basic C# Generic Predicate Delegate

Find a very useful (practical) example of combining generic, predicate, and delegate together on the List (removing items in the list).

//create a list of candidates
List candidates = new List();
for (int i=2; i <= 100; i++) { candidates.Add(i); } //use predicate and delegate to remove the items on the list candidates.RemoveAll (delegate(int x) { return x>2&& x%2==0; }
);

//or use the predicate only
candidates.RemoveAll(RemoveUnWantedItems);

static bool RemoveUnWantedItems(int x)
{
return (x>2&& x%2==0;);
}

Thursday, May 01, 2008

Passing Value-Type parameters vs Passing Reference-Type parameters

In the real world coding, I rarely think about this issue much. The debugger always shows the values for you when you debug the application. However, when taking an exam (or interview), you will get a question about it and you are asked what is the output look like on the blank paper.

Again, the MSDN reference helped a lot. It listed all the examples with output. Here is the link:
http://msdn.microsoft.com/en-us/library/0f66670z(VS.71).aspx