Thanks to visit codestin.com
Credit goes to github.com

Skip to content

System.InvalidCastException F# snippets #7772

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module Interface1

// <Snippet3>
open System
open System.Globalization

let culture = CultureInfo.InvariantCulture
let provider: IFormatProvider = culture

let dt = provider :?> DateTimeFormatInfo

// The example displays the following output:
// Unhandled Exception: System.InvalidCastException:
// Unable to cast object of type //System.Globalization.CultureInfo// to
// type //System.Globalization.DateTimeFormatInfo//.
// at Example.main()
// </Snippet3>
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module ToString1

// <Snippet4>
let value: obj = 12
// Cast throws an InvalidCastException exception.
let s = value :?> string
// </Snippet4>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module ToString2

// <Snippet5>
let value: obj = 12
let s = value.ToString()
printfn $"{s}"
// The example displays the following output:
// 12
// </Snippet5>
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
module basetoderived1

// <Snippet1>
open System

type Person() =
member val Name = String.Empty with get, set

type PersonWithId() =
inherit Person()
member val Id = String.Empty with get, set


let p = Person()
p.Name <- "John"
try
let pid = p :?> PersonWithId
printfn "Conversion succeeded."
with :? InvalidCastException ->
printfn "Conversion failed."

let pid1 = PersonWithId()
pid1.Name <- "John"
pid1.Id <- "246"
let p1: Person = pid1
try
let pid1a = p1 :?> PersonWithId
printfn "Conversion succeeded."
with :? InvalidCastException ->
printfn "Conversion failed."

// The example displays the following output:
// Conversion failed.
// Conversion succeeded.
// </Snippet1>
14 changes: 14 additions & 0 deletions snippets/fsharp/System/InvalidCastException/Overview/fs.fsproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Include="iconvertible1.fs" />
<Compile Include="basetoderived1.fs" />
<Compile Include="Interface1.fs" />
<Compile Include="ToString1.fs" />
<Compile Include="ToString2.fs" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module iconvertible1

// <Snippet2>
open System

let flag = true
try
let conv: IConvertible = flag
let ch = conv.ToChar null
printfn "Conversion succeeded."
with :? InvalidCastException ->
printfn "Cannot convert a Boolean to a Char."

try
let ch = Convert.ToChar flag
printfn "Conversion succeeded."
with :? InvalidCastException ->
printfn "Cannot convert a Boolean to a Char."

// The example displays the following output:
// Cannot convert a Boolean to a Char.
// Cannot convert a Boolean to a Char.
// </Snippet2>
5 changes: 5 additions & 0 deletions xml/System/InvalidCastException.xml
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ For a list of initial property values for an instance of <xref:System.InvalidCas
You directly or indirectly call a primitive type's <xref:System.IConvertible> implementation that does not support a particular conversion. For example, trying to convert a <xref:System.Boolean> value to a <xref:System.Char> or a <xref:System.DateTime> value to an <xref:System.Int32> throws an <xref:System.InvalidCastException> exception. The following example calls both the <xref:System.Boolean.System%23IConvertible%23ToChar%2A?displayProperty=nameWithType> and <xref:System.Convert.ToChar%28System.Boolean%29?displayProperty=nameWithType> methods to convert a <xref:System.Boolean> value to a <xref:System.Char>. In both cases, the method call throws an <xref:System.InvalidCastException> exception.

:::code language="csharp" source="~/snippets/csharp/System/InvalidCastException/Overview/iconvertible1.cs" interactive="try-dotnet" id="Snippet2":::
:::code language="fsharp" source="~/snippets/fsharp/System/InvalidCastException/Overview/iconvertible1.fs" id="Snippet2":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.invalidcastexception/vb/iconvertible1.vb" id="Snippet2":::

Because the conversion is not supported, there is no workaround.
Expand All @@ -123,6 +124,7 @@ For a list of initial property values for an instance of <xref:System.InvalidCas
You are downcasting, that is, trying to convert an instance of a base type to one of its derived types. In the following example, trying to convert a `Person` object to a `PersonWithID` object fails.

:::code language="csharp" source="~/snippets/csharp/System/InvalidCastException/Overview/basetoderived1.cs" interactive="try-dotnet" id="Snippet1":::
:::code language="fsharp" source="~/snippets/fsharp/System/InvalidCastException/Overview/basetoderived1.fs" id="Snippet1":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.invalidcastexception/vb/basetoderived1.vb" id="Snippet1":::

As the example shows, the downcast succeeds only if the `Person` object was created by an upcast from a `PersonWithId` object to a `Person` object, or if the `Person` object is `null`.
Expand All @@ -132,6 +134,7 @@ For a list of initial property values for an instance of <xref:System.InvalidCas
You are attempting to convert an interface object to a type that implements that interface, but the target type is not the same type or a base class of the type from which the interface object was originally derived. The following example throws an <xref:System.InvalidCastException> exception when it attempts to convert an <xref:System.IFormatProvider> object to a <xref:System.Globalization.DateTimeFormatInfo> object. The conversion fails because although the <xref:System.Globalization.DateTimeFormatInfo> class implements the <xref:System.IFormatProvider> interface, the <xref:System.Globalization.DateTimeFormatInfo> object is not related to the <xref:System.Globalization.CultureInfo> class from which the interface object was derived.

:::code language="csharp" source="~/snippets/csharp/System/InvalidCastException/Overview/Interface1.cs" id="Snippet3":::
:::code language="fsharp" source="~/snippets/fsharp/System/InvalidCastException/Overview/Interface1.fs" id="Snippet3":::
:::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.invalidcastexception/vb/Interface1.vb" id="Snippet3":::

As the exception message indicates, the conversion would succeed only if the interface object is converted back to an instance of the original type, in this case a <xref:System.Globalization.CultureInfo>. The conversion would also succeed if the interface object is converted to an instance of a base type of the original type.
Expand All @@ -141,13 +144,15 @@ For a list of initial property values for an instance of <xref:System.InvalidCas
You are trying to convert a value or an object to its string representation by using a casting operator in C#. In the following example, both the attempt to cast a <xref:System.Char> value to a string and the attempt to cast an integer to a string throw an <xref:System.InvalidCastException> exception.

:::code language="csharp" source="~/snippets/csharp/System/InvalidCastException/Overview/ToString1.cs" id="Snippet4":::
:::code language="fsharp" source="~/snippets/fsharp/System/InvalidCastException/Overview/ToString1.fs" id="Snippet4":::

> [!NOTE]
> Using the Visual Basic `CStr` operator to convert a value of a primitive type to a string succeeds. The operation does not throw an <xref:System.InvalidCastException> exception.

To successfully convert an instance of any type to its string representation, call its `ToString` method, as the following example does. The `ToString` method is always present, since the <xref:System.Object.ToString%2A> method is defined by the <xref:System.Object> class and therefore is either inherited or overridden by all managed types.

:::code language="csharp" source="~/snippets/csharp/System/InvalidCastException/Overview/ToString2.cs" interactive="try-dotnet" id="Snippet5":::
:::code language="fsharp" source="~/snippets/fsharp/System/InvalidCastException/Overview/ToString2.fs" id="Snippet5":::

<a name="Migration"></a>
## Visual Basic 6.0 migration
Expand Down