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

Thursday, April 16, 2009

my solution to Eric Lippert's quiz

Eric posted a quiz a few days ago, it generated quite a number of responses, so I thought I would answer with the shortest possible C# answer (with my previous team we used to kinda compete on refactoring), so here it is (Justin and Paul, bring it on!):
The problem:
Write me a function that takes a non-null IEnumerable and returns a string with the following characteristics:

(1) If the sequence is empty then the resulting string is "{}".
(2) If the sequence is a single item "ABC" then the resulting string is "{ABC}".
(3) If the sequence is the two item sequence "ABC", "DEF" then the resulting string is "{ABC and DEF}".
(4) If the sequence has more than two items, say, "ABC", "DEF", "G", "H" then the resulting string is "{ABC, DEF, G and H}". (Note: no Oxford comma!)


My solution:

static string JoinStrings(IEnumerable<string> strings) {

int len = strings.Count();

return "{"+(

(len > 1) ?

strings.Take(len - 1)

.Aggregate((string head, string tail) => head+", "+tail)+

" and " +strings.Last()

: (len == 1) ?

strings.First()

: "")+

"}";

}

Thursday, April 02, 2009

Did you know? Interface members are allowed to be private

This one comes as a surprise to most people, but it is possible to have a private implementation for an interface member, let's look at a very simple example, just for purposes of the ilustration.

public interface ITest {

void Test();

}

public class Test : ITest {

void ITest.Test() {

Console.WriteLine("test");

}

public void Test2() {

Console.WriteLine("test2");

}

}

class Program {

static void Main(string[] args) {

ITest t = new Test();

t.Test();

Test t2 = new Test();

//t2.Test(); //<<=== doesn't compile


If you don't believe it you can try it of course.

But why is this useful or how do you use this?

The technique allows you to ensure that the method is only visible to those who are using a variable of the interface type. All this does is to force the use of the member through an instance of the interface, meaning, for this example, if you want to get access to the .Test method, you can only do so through a variable of type ITest.

The only trick to make this work is to precede the member declaration with the Interface type as in:

void ITest.Test();

Not the most useful of tricks, but something to have on the bag of tricks, or maybe something to make you win a bet ;)

Saturday, September 27, 2008

string format gotcha

here's a simple, inoffensive looking piece of code:

...
LogError(string.Format("some message, some variable value {0}" + ex.Message, varValue));
...

Can you spot the problem with this code?

Thursday, January 10, 2008

C# vNext wishlist: comma less argument list

Mitch Denny has a post about his feature request for the next version of C#

he wants to have a shortcut to format strings, which would basically allow you to go from this
string s=string.Format(”{0}{1}{2}”, a, b, c);
to this:
string s=@(”{0}{1}{2}”|a|b|c);

I don't think I like the proposed alternative, all you are doing is replacing the "," with the "|" character and making the name shorter.
You could always write your own little wrapper:
//*** you could call it "f" if you wanted
static string fmt(string format, params object[] parameters) {
return string.Format(format, parameters);
}

and get
string s=fmt("{0}{1}{2}",a,b,c);

which is almost the same as the proposed solution

another problem is that this proposal solves a very particular problem which is string formatting and we can get pretty much the same by writing our own little wrapper

but anyway, it gave me an idea for my own feature request
comma-less arguments

string s=fmt("{0}{1}{2}" a b c);

The scope of this change is much wider and actually "desugars" the language

now this change will most likely not happen, since this is a C family language and would take a significant change to the parser but this is my own wish/feature request so there you have it

Monday, October 15, 2007

small refactoring for working with nullable types

the article applies to: C# 2.0

C# 2.0 brought a new feature: nullable types, you already know they are cool and have been using them for a while, however, how many times have you seen (or written) something like:

//SomeClass.SomeObject.BoolProperty is of type bool?

if (SomeClass.SomeObject.BoolProperty.HasValue && SomeClass.SomeObject.BoolProperty.Value)...
//something

because you can't write:
if (SomeClass.SomeObject.BoolProperty)...

That will not compile

The problem I have with that code is that it is repetitive, and is long, so what can we do?
you can write this instead:

if (SomeClass.SomeObject.BoolProperty??false)

much better, isn't? if BoolProperty has a value and the value is true, it will return true, otherwise it will return false; now, of course you can use the same technique with other types:

string firstName;
public string FirstName { get{ return firstName??""; }}

this code would ensure that FirstName will never be null (I'm pretty sure you've seen lots of "object reference not set blablabla" because of this)

Other examples:
int? result;
...
return result??-1; //if result was not set, return -1
---------------------------------------------------
bool? result;
...
return result??false;
---------------------------------------------------

That's it, hope you find it useful
Remember that the best code, is no code at all

kick it on DotNetKicks.com

Thursday, September 27, 2007

Get last day of month

applies to: C#, .NET
In the spirit of sharing code, and I think this is the second time in this week that I need this function

DateTime GetLastDayOf(DateTime date) {
return new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
}

Saturday, June 09, 2007

C# Quiz #1: overloads, strings, nullable types

*This is also a test of the latest Windows Live Writer

given this class definition:

public class Foo {
public void Bar(string x) {
Console.WriteLine("string x was called");
}
public void Bar(int? x) {
Console.WriteLine("int? x was called");
}
}

what will be output to the console with the following code:

Foo f = new Foo();
try {
f.Bar(null);
}
catch {
Console.WriteLine("no method was called");
}

*update: I messed up the code while trying to upload another post, I recovered the original post from my RSS feed

Friday, May 18, 2007

.NET user control not loading under https

keywords: .net user control, activex, ocx, IE7, IE, https, http, secure

Justin and I just had a heck of a week fighting ActiveX controls developed using C# in .NET 2.0, so we will be blogging about some of the issues that we found and their solutions (so we can remember later), the first one is about ActiveX controls running under https.

We developed our control, everything was fine, one of our clients wanted to try that over a secure site, so we said no problem... until we tried, and tried, and tried, and nothing worked, the control would just not load.

the solution ended up being really stupid (as is usually the case); when you include your control, you usually do something like this:

<object id="someId" classid="SomeDll#Namespace.ClassName"></object>

that's the way you'll find it in all the examples around the web, and that will work just fine (once you get past all the other stuff that is required to make it work) under http, but when you move that to https, it will simply not work.

the solution?

when you create your control, you assign a guid to it

[Guid("CAE67AEA-F489-4e52-956B-CCC774F40A3A")]
[ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(IControlEvents))] // --Expose events
[ComVisible(true)]
public partial class MyControl : UserControl...

something like that...
well, to make it work on https, you simply have to use that GUID, not the class name, so you would just write this on your html code

<object id="someId" classid="clsid:CAE67AEA-F489-4e52-956B-CCC774F40A3A"></object>

done, hope we saved you hours of headache

Thursday, February 08, 2007

protected, internal, protected internal... are you sure you know them?

the code for this article applies to C#

We all take access modifiers for granted, but can you tell me what protected internal does?

I bet more than half .NET developers will get that wrong, let's review:
  1. private:
    1. This is the least permissive access level.
    2. Accessible only within the body of the class or the struct in which they are declared.
    3. Nested types in the same body can also access those private members
  2. public:
    1. This is the most permissive access level.
    2. There are no restrictions on accessing public members, they are visible anywhere the class is visible
  3. protected:
    1. Access is limited to the containing class or types derived from the containing class.
    2. which means you cannot create an instance of a class and have access to protected members.
  4. internal:
    1. Access is limited to the current assembly.
  5. protected internal:
    1. Access is limited to the current assembly or types derived from the containing class.
that last one is kinda tricky, it kinda "makes sense" that it allows access only in the current assembly and the current or derived classes, but the "or" there is what makes a difference, if you mark a property protected internal, it can actually be accessed outside the assembly. basically protected overrides internal and so I'm not even sure when it makes sense to use such modifier.

If you don't believe me go check it out your self:
Assembly1:
public class Test {
protected internal string prop1;
}

Assembly2://after adding a reference to Assembly 1
public class Test2: Test {
public string prop2;
public Test2() {
prop2 = prop1; //came from the other assembly's class protected internal member
}
}

if this is news for you, you might think, that's stupid, how do you get a property to be visible only the the current assembly, current class and derived classes?

quite simple, you mark your class as internal, so your class can only be accessed from the current assembly, and you mark your property as protected, thus giving access to the derived classes only in the current assembly:

internal class Test {
protected string prop1; //accessible only in this assembly in this class and derived classes
}

Monday, January 29, 2007

formatting 0, 1 as yes, no or whatever

This is something we all have done at some point, convert a 0,1 value into yes, no, on, off, etc string

turns out there is a function in the BCL that can do this, string.Format will do the job

Console.WriteLine(string.Format("{0:yes;;no}", 0)); //will output "no"
Console.WriteLine(string.Format("{0:yes;;no}", 1)); //will ouput "yes"


and just for the heck of it
Console.WriteLine(string.Format("{0:yes;;no}", -1)); //will output "-yes"

...one of those little thingies

Wednesday, December 20, 2006

function to generate random numbers, without repeating digits

The code for this article applies to C#

Reading blogs, I found this post (in italian), where Marco wants to write a function to generate random numbers with the following rules:

  • 5 digits long
  • result should be returned in a string
  • all the digits should be different (on each result you can't have two of the same digit)

The function he came up with was the following:

private string GetRandom()
{
Random rn = new Random();
string resultnum=string.Empty;
do
{
string a = rn.Next(0, 9).ToString();
if (resultnum.Contains(a)!=true)
resultnum = resultnum + a;
}
while (resultnum.Length<5);
return resultnum;
}

I felt curious to see what areas I could improve, and I started writing a function to get the same result, but in a more optimized way

A couple things that jump out to my mind are:

  1. string concatenation
  2. the loop and comparing each time to see if the digit is in the result already

So I wanted to write a function that: would avoid concatenation and would execute the loop exactly 5 times, this is the result:

static char[] allNumbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
Random r = new Random();
public string GetRandom2() {

char[] result = new char[5];
int max = 9, pos=0;
for (int i=1; i<6; i++) {
pos = r.Next(0, max);
result[i - 1] = allNumbers[pos];
//*** swap positions
allNumbers[pos] ^= allNumbers[max];
allNumbers[max] ^= allNumbers[pos];
allNumbers[pos] ^= allNumbers[max--];
}
return new string(result);
}

The technique I used was:

  • Have a predefined array with all possible characters
  • I have a variable max that I use to call the method Random.Next(0, max)
  • the variable is decremented on each iteration
  • I swap the digit from the result to the last position, with this I leave this digit out of the posibilities for the next call

The performance gain from these changes was minimal (3 ms per 1000 calls), then I thought about moving the Random variable declaration outside the function, so it could be reused between calls, this gave me the performance gain I was looking for, calling the function 10,000 times takes ~114ms using the old method and only ~6ms using the new one, that's where the problem was, the rest was pretty much insignificant =o(

I'm sure someone else can write a faster version, but I accomplished my goal =o)

Sunday, December 17, 2006

Get (another's class) private fields

About 2 months ago I wrote a couple articles on reflection, specifically about executing another's class private methods, someone left a question on how you can get the private fields, just now I found the time to answer to that; first of all let's create a test class:

class TestClass {
private int prop1;

public int Prop1 {
get { return prop1; }
set { prop1 = value; }
}

private string prop2;

public string Prop2 {
get { return prop2; }
set { prop2 = value; }
}

private bool prop3;

public bool Prop3 {
get { return prop3; }
set { prop3 = value; }
}

public bool field4;

public TestClass() {
prop1 = 10;
prop2 = "20";
prop3 = false;
field4 = true;
}
}



Then we create an instance of it, and use the method GetFields to (you guessed) get the list of fields, we just have to specify on the parameters that we want private members and they have to be instance members (non-static), once we get the list we can do *whatever* we want with it, in this case the code prints the field type and it's value


TestClass test = new TestClass();
FieldInfo[] fields = test.GetType().GetFields(BindingFlags.NonPublic BindingFlags.Instance);
foreach (FieldInfo f in fields)
Console.WriteLine(string.Format("type:{0} \t value:{1}", f.FieldType.ToString(), f.GetValue(test)));


That's about it. Now, just to make it a little bit more interesting I created a small generic function to accomplish the previous task and now you can reuse that with any other class:

static void PrintPrivateFields<T>(T theInstance) where T:class {
Type t = theInstance.GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic BindingFlags.Instance);
foreach (FieldInfo f in fields)
Console.WriteLine(string.Format("type:{0} \t value:{1}", f.FieldType.ToString(), f.GetValue(theInstance)));
}



To use it, we just create an instance of that class and pass the instance to the function:


TestClass test = new TestClass();


PrintPrivateFields(test);


Note that I don't need to specify the type when calling the function


PrintPrivateFields<TestClass>(test);


The compiler is smart enough to figure it out (since the only parameter is of that type).


Hope the code is useful, you can find the full code here