mscorlib Source Stream should throw a StackOverflowException

88 views Asked by At

I was take a read in the .net source code more specifically ito the mscorlib source and I stoped to see how the Stream Class was implemented, everything as fine and all untill I saw this line of Code:

public static readonly Stream Null = new NullStream();

And then I thougth "So NullStream is derived from Stream wait should that not throw an exception?".

This is what have gone through my mind: codeflow and here is the sourcecode the path to the stream is:

Project->mscorlib Path=>system/io/stream.cs

1

There are 1 answers

0
niceman On BEST ANSWER

StackOverflowException is expected with this code:

public readonly Stream Null=new NullStream()

because calling NullStream constructor will call Stream constructor(the parent class)which must initialize Null field which then call NullStream()....
but hey it's static ! initialization of static fields are done just once and before any object is created, calling NullStream() will call Stream() but the latter won't initialize Null because constructors don't initialize static fields(except static constructors which we don't have here).
even if we had static constructor it's called just once either and before any object is created.