Ian (Fluxtah) Warwick's blog RSS 2.0
# Monday, March 01, 2010

First 16 numbers of the fibonacci series

void Main(){ for(long i=0, n=0, a = 1, b = 0; i < 16; i++,  Console.WriteLine(n), b = a, a = n, n = a + b); }
Monday, March 01, 2010 12:26:57 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#
# Wednesday, November 25, 2009

I was thinking about this, for some reason, and thought it would be good to remind myself of those little useful bits of code that you never really use much then sometimes wonder how to do them.

So my first tidbit, is to test if a number is a whole number, here is my solution, any better solution than this, answers on a postcard please.

void Main()
{
    decimal decimalNumber = 4.9M;
    decimal wholeNumber = 5;
    
    Console.WriteLine(Math.Floor(decimalNumber) == decimalNumber); // Returns false;
    Console.WriteLine(Math.Floor(wholeNumber) == wholeNumber); // Returns true;
}

 

Wednesday, November 25, 2009 10:39:40 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#
# Friday, November 13, 2009

I wrote a small console application to test if this was possible and it turns out all you need is an XmlInclude attribute on the base type of the sub-types you are serializing.

In the following example Ninja and Customer inherit from Person, Person is decorated with the XmlInclude attribute for both Ninja and Customer.

class Program
 {
     static void Main(string[] args)
     {
         XmlSerializer serializer = new XmlSerializer(typeof(Stuff));
         Stuff stuff = new Stuff()
         {
             People = new List<Person>()
             {
                 new Person() { Name = "<b>Bob</b>", Type="Person" },
                 new Ninja() { Name = "Hiro", Type="Ninja", Weapon = "Shuriken" },
                 new Customer() { Name = "Fred", Type = "Customer", CustomerId = "1234"}
             }
         };

         serializer.Serialize(Console.Out, stuff);
     }
 }

 public class Stuff
 {
     public List<Person> People { get; set; }
 }

 [XmlInclude(typeof(Ninja)), XmlInclude(typeof(Customer))]
 public class Person
 {
     public string Type { get; set; }
     public string Name { get; set; }
 }

 public class Ninja : Person
 {
     public string Weapon { get; set; }
 }

 public class Customer : Person
 {
     public string CustomerId { get; set; }
 }
Friday, November 13, 2009 7:56:37 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#
# Tuesday, September 15, 2009

Whilst working on my network engine I came across a problem that I initially solved with an interface, but it turned out that the class that implemented this interface exposed public methods that I really wanted to be private, an example will explain the problem.

public interface IMessageReceiver
{
    void Receive(string message);
}

public interface IMessageProvider
{
    IMessageReceiver MessageReceiver;
    void Update();
}

public class ConcreteReceiver: IMessageReceiver
{
    private IMessageProvider _MessageProvider;

    public ConcreteReciever(IMessageProvider messageProvider)
    {
        _MessageProvider = messageProvider;
        _MessageProvider.MessageReceiver = this;
    }
    public void Receive(string message)
    {
        Console.WriteLine(message);
    }

    public void Update()
    {
        MessageProvider.Update();
    }
}

When calling ConcreteReceiver.Update(), this will call MessageProvider.Update(), then, the concrete implementation of IMessageProvider should call IMessageReceiver.Receive, effectively like a callback.

Now the issue in my case was that I did not want the Receive method of ConcreteReceiver to be public, but of course any concrete type that implements an interface must implement those methods as public, after pondering a while I realised the design was actually flawed anyway, what I really wanted was a callback, so I changed my design as follows.

public interface IMessageProvider
{
    Action<string> ReceiveAction;
    void Update();
}

public class ConcreteReceiver
{
    private IMessageProvider _MessageProvider;

    public ConcreteReciever(IMessageProvider messageProvider)
    {
        _MessageProvider = messageProvider;
        _MessageProvider.ReceiveAction = Receive;
    }
    private void Receive(string message)
    {
        Console.WriteLine(message);
    }

    public void Update()
    {
        MessageProvider.Update();
    }
}

So now my Receive method on my ConcreteReceiver can be private, since I am now using a generic Action<T> delegate, this prevents my public API exposing methods that are really meant to be only used internally.

Tuesday, September 15, 2009 3:50:00 AM (GMT Daylight Time, UTC+01:00)  #    Comments [1] -
C#
# Wednesday, September 09, 2009

The Available property of the System.Net.Sockets class will tell you how much data is available to read.

With UDP sockets, one thing to remember is that Socket.Available will give the total size of all the datagrams ready to read, so to the only way to know how many datagrams are waiting to be read is to call ReceiveFrom repeatedly until all data is read, for instance:-

while(Socket.Available > 0)
{
   int datagramSize = Socket.ReceiveFrom(buffer, ref endPoint);
} 

The datagramSize variable will give the size of the datagram that was read, this can be troublesome to manage since you do not know what you are going to get, until you get it, so you would need to initialize a large enough buffer to hold the datagram.

In the networking framework I am currently writing, the application has a configurable MaxPacketSize option so I can initialize my buffer to this size, but this wont help in the event that a bum packet is sent that breaches this constraint so some error handling would also need to be in place to compensate for this issue.

Wednesday, September 09, 2009 5:26:00 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
C#
# Thursday, March 05, 2009

Another keyword I have not used much is the new modifer, the MSDN docs for the new Modifer open up with the following:-

When used as a modifier, the new keyword explicitly hides a member inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base-class version. Although you can hide members without the use of the new modifier, the result is a warning. If you use new to explicitly hide a member, it suppresses this warning and documents the fact that the derived version is intended as a replacement.

The new modifier has an interesting but important effect when casting, as the following example demonstrates. 

class Program
 {
     public class Animal
     {
         public void Say()
         {
             Console.WriteLine("I am an animal!");
         }
     }
     public class Cat : Animal
     {
         public new void Say()
         {
             Console.WriteLine("Meeeoooooww!");
         }
     } 
     public class WildCat : Cat
     {
         public new void Say()
         {
             Console.WriteLine("ROAR!");
         }
     } 

     static void Main()
     {
         WildCat wildCat = new WildCat();
         Cat cat = wildCat;
         Animal animal = cat; 

         wildCat.Say();
         cat.Say();
         animal.Say();
     }
 }

The code outputs the following.

ROAR!
Meeeoooooww!
I am an animal! 

The code demonstrates when downcasting, WildCat and Cat use their own implementations of Say(), I am not sure I would want that type of behaviour, since it could be rather dangerous if its not used intentionally, but its interesting to know anyway.

Thursday, March 05, 2009 11:28:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#
    public abstract class Animal{}
    public class Cat : Animal
    {}
    public class Ornament
    {
        public static explicit operator Ornament(Cat cat)
        {
            return new Ornament();
        }
    } 

    class Program
    {
        static void Main()
        {
            Cat cat = new Cat(); 

            // This line fails to compile
            Ornament jug = cat as Ornament; 

            // this works with our explicit operator defined for Ornament
            Ornament anotherJug = (Ornament)cat;        
        }
    }

Well the holes in my C# knowledge never cease to amaze me, I mean, I knew what I could do with the as keyword but I did not know the subtle difference it has to a direct cast.

By using the as keyword to cast from one type to another, if the cast is not possible it will result in a null, however using a direct cast will throw an exception.

An example demonstrates the use of the as keyword.

    public abstract class Animal{}
    public class Cat : Animal{}
    public class Ornament{} 

    class Program
    {
        static void Main()
        {
            object cat = new Cat(); 

            // jug will be null after this conversion since
            // cat is not an Ornament
            Ornament jug = cat as Ornament;

            // this throws an InvalidCastException
            jug = (Ornament) cat; 

            // This works since Cat is an Animal, animal will not
            // have a reference to cat
            Animal animal = cat as Animal; 

        }
    }

Quite handy really, but there is one thing to note, notice that we say object cat = new Cat();? This is because we get a compilation error if we had used Cat cat = new Cat();

Cannot convert type 'ConsoleApplication1.Cat' to 'ConsoleApplication1.Ornament' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

The reason for this (I believe) is because of the limitation described in the MSDN Docs for the as keyword.

Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

An example below shows this, it has been slightly modified by adding an explicit cast operator to Ornament so we can use a cast expression for anotherJug to show the difference between a cast and a conversion with the as keyword, so as the docs say:- user-defined conversions do not work with the as keyword.

kick it on DotNetKicks.com
Thursday, March 05, 2009 6:01:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#

Well, smack me with a wet kipper, I have never really considered the difference between do and do while, since I have always just used a while loop.

Anyway, the difference is, that a do-while will always execute before checking the condtion, whereas a while loop, checks the condition before executing the code block.

Quite a fundamental difference that could prove to be useful, I definetly see a 'gotcha!' interview question from this one if it was ever asked.

class Program
 {
     static void Main()
     {
         int x = 0; 

         // Will always output "Hello World"
         do
         {
             Console.WriteLine("Hello World");
             x++;
         } while (x <= 0); 

         // Will not output anything
         while (x <= 0)
         {
             Console.WriteLine("Hello World");
             x++;
         }
     }
 }
Thursday, March 05, 2009 4:40:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#

I had a great job interview for a great company on tuesday just gone, they are a Microsoft Gold Certified Partner so that suits me down to the ground since I am a Microsoft fanboy! I have a second stage interview with them that will be technical, so it would probably involve a test and lots of questions, so I have decided to put in some more study into my profession and brush up on stuff, starting with C#.

I think myself as a fairly good C# programmer, not the best, but fairly good, but, there are some things that I have never needed to learn, in this post I will look at the checked keyword. The checked keyword is used to control the overflow-checking context of integral-type arithmetic operations and conversions - cited from the msdn docs.

At first glance, since some things are not always clear to me, my thoughts are - what does this mean?

Well, if we take a byte, we know that a byte can only have maximum value of 255, so any greater value than 255 would result in an overflow.

So what checked does is - if you perform an arithmetic operation that results in an overflow, it will throw an OverflowException, the following example shows this.

 class Program
 {
     static void Main()
     {
         byte a = 200;
         byte b = 200; 

         byte c = checked((byte)(a + b)); 

         Console.WriteLine(c);
     }
 }

Without the checked, the calculation would wrap giving c a value of 144.

I have never needed to use this yet, but I guess if an important calculation was being performed then I would consider it, for instance if it was going to lose a lot of money!

Thursday, March 05, 2009 3:43:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
C#
# Thursday, February 12, 2009

Recently at a job interview during a technical test I had to answer a question:

What is the difference between a delegate and a multicast delegate?

Unfortunately I did not have the answer, I have used delegates plenty but I have never obviously used them enough to know this difference, and the dissapointing thing is that the answer was glaringly obvious.

A multicast delegate is multiple instances of the same delegate chained together using the + operator, Events in .NET make use of this to attach multiple event handlers to an event.

An example: 

public delegate void SaySomething(string something);

 class Program
 {
     static void Main(string[] args)
     {
         // At first, something is just a delegate
         SaySomething something = new SaySomething((s) => Console.WriteLine(s));

         // By adding together more instances of the SaySomething delegate.
         // we get a multicast delegate
         something += new SaySomething((s) => Console.WriteLine(s.ToUpper()));
         something += new SaySomething((s) => Console.WriteLine(s.ToLower()));

         something("Hello");
     }
 } 

The output would give:

Hello
HELLO
hello

It pains me to think I have now been at this for 6 years and there are still aspects to C# that I have not yet come across, yet I do not think of myself as a bad developer, I am sure there are plenty of things that I am aware of that the interviewer has no idea about, and it makes me wonder if the whole point is to see areas of where I could improve my knowledge, or the purpose is to scrutinise my knowledge in a way that an incorrect answer would make me out to be some kind of fraud.

I guess at least now if this question comes up again I will be able to answer it.

Thursday, February 12, 2009 6:20:00 AM (GMT Standard Time, UTC+00:00)  #    Comments [3] -
C#
Archive
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Ian Warwick
Sign In
Statistics
Total Posts: 33
This Year: 0
This Month: 0
This Week: 0
Comments: 4
Themes
Pick a theme:
All Content © 2012, Ian Warwick
DasBlog theme 'Business' created by Christoph De Baene (delarou)