2

The following all work perfectly in PowerShell, but they can't even compile in C# in Visual Studio:

D:\> $dow = [DayOfWeek]'Monday'
D:\> $dow.ToInt32($null)
1
D:\> $dow.value__
1

Why is this so?

Thanks.

1

3 Answers 3

3

Because PowerShell and C# are completely different systems.

C# is a strongly-typed compiled language and PowerShell is a scripting language. Just like C# is different from VBA, it is different from PowerShell, which in turn is also different from VBA.

So each has unique features, some are the same in different environments must most features are not.

Sign up to request clarification or add additional context in comments.

7 Comments

That doesn't mean it supports the same features or shares any syntax rules.
true, but in this case I'm pretty sure it's because enums do implement a ToInt32 method, which any .NET language can call; this is not specific to PowerShell. The fact that it's directly accessible in PS, though, is probably specific to PS (other languages don't allow to call methods of explicitly implemented interfaces directly)
"So each has unique features, some are the same in different environments must most features are not."
I second Thomas Levesque. The same property of the same CLR object should be available in both. I don't think it is a syntax issue in this case.
@OldGeezer 2nd is ((IConvertable)dow).ToInt32(null) (enum implicitly implements IConvertable and not supplying a IFormatProvider defaults to the thread's default culture). 3rd is the implementation of enum types (take a look at the fields of an enum types in a decompiler); but most tools (including the C# compiler and VS) hide this.
|
2

My guess is this is because all enums implement IConvertible. In C# the ToInt32 method is not directly visible because the interface is implemented explicitly, but Powershell probably has different rules.

Comments

2

For the most part C# is a statically typed langauge while PowerShell is mostly dynamically typed. Basically that means that type checking is done at compile time in C# (excluding dynamic code blocks) and type checking is done at runtime in PowerShell.

C# also has type safety which prevents you treating a value of one type as a value of another type. Hence you will get a compile error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.