Friday, 15 March 2013

c# - Static class doesn't get called first but instance class. Why? -



c# - Static class doesn't get called first but instance class. Why? -

i aware that, static constructors take precedence , called first before instance constructors. consider scenario of me having 1 instance class , 1 static class. wondering why results first base of operations class , static class ? have verified interchanging calling, result accordingly. wrong in thoughts that, static classes should called first irrespective of other instance classes ? why raised me because, saw somewhere that, static classes loaded automatically when namespace containing class triggered. expect static constructor fire first. why not happening ? please explain in understandable , simple way.

public class base of operations { public base() { console.writeline(" normal base of operations constructor"); } static base() { console.writeline("hey static base"); } } public static class base1 { static base1() { console.writeline("i static constructor"); } public static void staticmethod() { console.writeline("i static method"); } } static void main(string[] args) { base of operations b = new base(); base1.staticmethod(); console.read(); }

static constructors called if needed. if needed, guaranteed called before normal constructors class.

but there no guarantee static constructors called before normal constructor different class.

it wouldn't possible , avoid calling static constructors aren't used. access class static constructor before programme terminates, , if status satisfied. clearly, code couldn't peer ahead in time determine whether or not static constructor phone call needed; therefore, there no way phone call static constructor before code accesses it.

check out eric lippert's blog static constructors many more details!

c# .net static

No comments:

Post a Comment