RSS

Tag Archives: c#

C# Dynamic-Typed Parameter Trap

A little tricky lesson today in C#.

Passing a dynamic-typed parameter to a method that has defined return type (ie: string, int, etc) will not return the defined type, instead the method will return dynamic type.

class Program
{
	static void Main(string[] args)
	{
		FooBarClass fooBar = new FooBarClass();

		var result1 = fooBar.Foo("Foo");

		dynamic bar = "Bar";
		var result2 = fooBar.Foo(bar);
	}
}

public class FooBarClass
{
	public string Foo(string fooArg)
	{
		return "This is Foo";
	}
}

In the above example, type of result1 is string, but type of result2 is dynamic, even though they both call same method that return string type.
result1
result2

This is because compiler do not evaluate dynamic type until runtime therefore it can’t determine return type at compile time.

This is important to point out because if we apply extension method to result2, it will throw exception at runtime, not compile time.

Example of extension method.

public static class FozBazClass
{
	public static void Foz(this string fozArg)
	{
		fozArg = "Test..." + fozArg;
	}
}
result1.Foz(); // this will execute normally
result2.Foz(); // this will throw exception

result2 exception

Just another reason we should avoid dynamic type.

Advertisements
 
Leave a comment

Posted by on May 29, 2018 in General

 

Tags: , , , ,

String as a Reference Type and Immutable

In .Net, string object is reference type, however when we pass the value like this

void Main()
{
    string s = "Test";

    TestString(s);
    Console.WriteLine("TestString: " + s); // Output is: TestString: Test
}

public static void TestString(string s)
{
    s = "TestString";
}

Why is the output “TestString: Test”, we know for sure string is a reference type and we assign new value to our parameter in TestString() method.

Turn out, beside being a reference type, string is also an immutable, which mean its value can’t be modified or changed. So when we assign new value to our parameter in TestString() method, it actually create new string object. It acts like value type but it isn’t a value type, it’s a reference type with immutable behavior.

 
Leave a comment

Posted by on May 15, 2018 in General

 

Tags: , , , ,

Float, Double, Decimal Types and DivideByZeroException

Most of us know the difference between Float, Double and Decimal types in .Net is the precision.

  • Float 32 bit (7 digits)
  • Double 64 bit (15-16 digits)
  • Decimal 128 bit (28-29 digits)

But most of us scratch our head over this:

var numerator = 10;
var denominator = 0;
var resultNoException1 = (float)numerator / (float)denominator; // Result Infinity, does not throw exception
var resultNoException2 = (double)numerator / (double)denominator; // Result Infinity, does not throw exception
var resultException = (decimal)numerator / (decimal)denominator; // Throw DivideByZeroException

Suffice to say throw/catch block won’t caught any exception on resultNoException1 and resultNoException2.

Why?

Because Float and Double types are binary floating point types (or sometimes being referred to as floating point types) while Decimal is decimal floating point types.

From MSDN:

Dividing a floating-point value by zero doesn’t throw an exception; it results in positive infinity, negative infinity, or not a number (NaN), according to the rules of IEEE 754 arithmetic.

 

 
Leave a comment

Posted by on May 2, 2018 in General

 

Tags: , , , , , , ,

Left-Shift Operator Is Limited?

Why is left-shift operator with 32 result in lower number?

int i = 1;
(i << 0).Dump(); // Result is 1
(i << 1).Dump(); // Result is 2
(i << 2).Dump(); // Result is 3
(i << 3).Dump(); // Result is 8
(i << 10).Dump(); // Result is 1024
(i << 20).Dump(); // Result is 1048576
(i << 30).Dump(); // Result is 1073741824
(i << 31).Dump(); // Result is -2147483648
(i << 32).Dump(); // Result is 1 -> WHY?
 
Leave a comment

Posted by on March 6, 2018 in General

 

Tags: , ,

C# Bit Shorthand

1 << 0; // Result is 1
1 << 1; // Result is 2
1 << 2; // Result is 4
1 << 3; // Result is 8

The way this works is, the binary value of first operand (the left) is shifted by number of bits of the second operand. Something like this:

1 is 00001 in binary which is 1 << 0
2 is 00010 in binary which is 1 << 1
3 is 00100 in binary which is 1 << 2
So on, so forth.

Another way to look at it is "adding X zero in the first operand's binary, where X is second operand.".

The kicker is that, second operand is only the first 5 bits (low-order five bits), means 00000 to 11111 (which is 31)

Reference: MSDN << Operator

 
Leave a comment

Posted by on October 28, 2017 in General

 

Tags:

Indexer-Supported Collection in C#

Indexer is a faster way to search a list / collection in C#, no looping is necessary.

Classes that support indexer:

  • Array []
  • List<T>
  • Dictionary<Key, Value>
  • ILookup<Key, Value>

Classes that don’t support indexer:

  • IEnumerable<T>
  • HashSet<T>
  • ICollection<T>

For classes that don’t support indexer, there’s ElementAt LINQ extension method.

 
Leave a comment

Posted by on September 28, 2017 in General

 

Tags: , ,

Why Must Extension Methods Be Declared in a Static Class?

Some possible answers:

  • The purpose of Extension Methods is to make LINQ work and LINQ only needs extension methods to be in a static, non-generic, non-nested class.
  • Easier for compiler to work with. Compiler and VS’s Intellisense can easily locate the methods.
  • Grouping the helper methods together.

Sources:
https://stackoverflow.com/questions/3930335/why-are-extension-methods-only-allowed-in-non-nested-non-generic-static-class

https://stackoverflow.com/questions/7163823/why-must-c-sharp-extension-methods-be-defined-in-static-classes

 
Leave a comment

Posted by on September 20, 2017 in General

 

Tags: ,

 
%d bloggers like this: