Wednesday 21 October 2015

Polymorphism Powershell v5 Classes

I have been doing a lot of work lately with Microsoft's Desired State Configuration and creating custom class resources.  As the code is getting more complicated I came accross an instance where I wanted to extend a class to have different implementations put into a list.  After a quick google found no results I thought I would give it a go myself and sure enough it was just like c#


class Foo{
    [string]$SomePram
    Foo([string]$somePram){
        $this.SomePram = $somePram
    }
    [string]GetMessage(){
        return $null
    }
    [void]WriteMessage(){
        Write-Host($this.GetMessage())
    }
}

class Bar : Foo{
    Bar([string]$somePram): base($somePram){

    }
    
    [string]GetMessage(){
        return ("{0} Success" -f $this.SomePram)
    }
}


class Bar2 : Foo{
    Bar2([string]$somePram): base($somePram){

    }
    
    [string]GetMessage(){
        return ("{0} Success" -f $this.SomePram)
    }
}

[Foo[]]$foos = @([Bar]::new("Bar"), [Bar2]::new("Bar2"))

foreach($foo in $foos){
    $foo.WriteMessage()
}

Wednesday 30 November 2011

Using Actions for Event Handlers

 

I had a thought to day that I would like to be able to build some event handling functionality at run time depending on one thing or another.

Rather than passing a method reference as the handler I wondered if you could pass an Action instead.  My first attempt did not work.

  1. var action = new Action<object, NubmerChangedEventArgs>((sender, eventArgs) =>
  2.     {
  3.         Console.WriteLine(String.Format("The number is now {0}", eventArgs.NewNumber));
  4.     });
  5.  
  6. var eventClass = new NumberTracker();
  7. eventClass.meh += action;

The above results in the following complier error

“Cannot implicitly convert type 'System.Action' to 'ConsoleApplication1.NumberChangedEventHandler'

However you can use the action to create an instance of the Event handler that can be used to handle the event.

  1. var action = new Action<object, NubmerChangedEventArgs>((sender, eventArgs) =>
  2.     {
  3.         Console.WriteLine(String.Format("The number is now {0}", eventArgs.NewNumber));
  4.     });
  5. var handler = new NumberChangedEventHandler(action);
  6.  
  7. var eventClass = new NumberTracker();
  8. eventClass.meh += handler;

In the end I did not require this ability as I ended up re-thinking the structure of my code.  But thought it was quite interesting none the less.