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

Skip to content

System.Activator F# snippets #7421

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 3 commits into from
Nov 29, 2021
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,37 @@
module ActivatorX

//<snippet1>
open System
open System.Reflection
open System.Text

type SomeType() =
member _.DoSomething(x) = printfn $"100 / {x} = {100 / x}"

//<snippet2>
// Create an instance of the StringBuilder type using Activator.CreateInstance.
let o = Activator.CreateInstance typeof<StringBuilder>

// Append a string into the StringBuilder object and display the StringBuilder.
let sb = o :?> StringBuilder
sb.Append "Hello, there." |> ignore
printfn $"{sb}"
//</snippet2>

//<snippet3>
// Create an instance of the SomeType class that is defined in this assembly.
let oh =
Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().Location, typeof<SomeType>.FullName)

// Call an instance method defined by the SomeType type using this object.
let st = oh.Unwrap() :?> SomeType

st.DoSomething 5
//</snippet3>

(* This code produces the following output:

Hello, there.
100 / 5 = 20
*)
//</snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Include="ActivatorX.fs" />
<Compile Include="source2.fs" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
module source2

//<snippet4>
open System

let instanceSpec =
"System.EventArgs;System.Random;System.Exception;System.Object;System.Version"

let instances = instanceSpec.Split ';'
let instlist = Array.zeroCreate instances.Length
let mutable item = obj ()

for i = 0 to instances.Length - 1 do
// create the object from the specification string
printfn $"Creating instance of: {instances.[i]}"
item <- Activator.CreateInstance(Type.GetType instances.[i])
instlist.[i] <- item

printfn "\nObjects and their default values:\n"

for o in instlist do
printfn $"Type: {o.GetType().FullName}\nValue: {o}\nHashCode: {o.GetHashCode()}\n"


// This program will display output similar to the following:
//
// Creating instance of: System.EventArgs
// Creating instance of: System.Random
// Creating instance of: System.Exception
// Creating instance of: System.Object
// Creating instance of: System.Version
//
// Objects and their default values:
//
// Type: System.EventArgs
// Value: System.EventArgs
// HashCode: 46104728
//
// Type: System.Random
// Value: System.Random
// HashCode: 12289376
//
// Type: System.Exception
// Value: System.Exception: Exception of type 'System.Exception' was thrown.
// HashCode: 55530882
//
// Type: System.Object
// Value: System.Object
// HashCode: 30015890
//
// Type: System.Version
// Value: 0.0
// HashCode: 1048575
//</snippet4>
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module remarks

// <Snippet1>
let factory<'T when 'T : (new: unit -> 'T)> =
new 'T()
// </Snippet1>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Include="remarks.fs" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module CreateInstance5
// <Snippet5>
open System

// Initialize array of characters from a to z.
let chars = [| 'a' .. 'z' |]

let obj = Activator.CreateInstance(typeof<string>, chars[13..22])

printfn $"{obj}"

// The example displays the following output:
// nopqrstuvw
// </Snippet5>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Include="..\personinfo.fs" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Compile Include="createinstanceex1.fs" />
<Compile Include="createinstanceex1a.fs" />
<Compile Include="createinstance2.fs" />
<Compile Include="CreateInstance5.fs" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="PersonInfo\PersonInfo.fsproj"/>
</ItemGroup>


</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module createinstanceex2
// <Snippet4>
open System

let chars = [| 'a' .. 'f' |]

let arguments =
[| chars
chars[1..4]
Array.create 20 chars[1] |]

for args in arguments do
let result =
Activator.CreateInstance(typeof<string>, args)

printfn $"{result.GetType().Name}: {result}"

// The example displays the following output:
// String: abcdef
// String: bcde
// String: bbbbbbbbbbbbbbbbbbbb
// </Snippet4>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
module createinstanceex1

// <Snippet2>
open System

let handle = Activator.CreateInstance("PersonInfo", "Person")
let p = handle.Unwrap() :?> Person
p.Name <- "Samuel"
printfn $"{p}"

// The example displays the following output:
// Samuel
// </Snippet2>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module createinstanceex1a

// <Snippet3>
open System

let handle =
Activator.CreateInstance("PersonInfo", "Person")

let p = handle.Unwrap()
let t = p.GetType()
let prop = t.GetProperty "Name"

if not (isNull prop) then
prop.SetValue(p, "Samuel")

let method = t.GetMethod "ToString"
let retVal = method.Invoke(p, null)

if not (isNull retVal) then
printfn $"{retVal}"

// The example displays the following output:
// Samuel
// </Snippet3>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace global

// <Snippet1>
type Person(name) =
member val Name = name with get, set

override this.ToString() = this.Name

new () = Person Unchecked.defaultof<string>

// </Snippet1>
9 changes: 9 additions & 0 deletions xml/System/Activator.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@

:::code language="cpp" source="~/samples/snippets/cpp/VS_Snippets_CLR/ActivatorX/cpp/ActivatorX.cpp" id="Snippet1":::
:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR/ActivatorX/cs/ActivatorX.cs" id="Snippet1":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR/ActivatorX/fs/ActivatorX.fs" id="Snippet1":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR/ActivatorX/VB/ActivatorX.vb" id="Snippet1":::

]]></format>
Expand Down Expand Up @@ -404,6 +405,7 @@

:::code language="cpp" source="~/samples/snippets/cpp/VS_Snippets_CLR/ActivatorX/cpp/source2.cpp" id="Snippet4":::
:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR/ActivatorX/cs/source2.cs" interactive="try-dotnet" id="Snippet4":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR/ActivatorX/fs/source2.fs" id="Snippet4":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR/ActivatorX/VB/source2.vb" id="Snippet4":::

]]></format>
Expand Down Expand Up @@ -571,16 +573,19 @@ Note: In <see href="https://go.microsoft.com/fwlink/?LinkID=247912">.NET for Win
The following example defines a class named `Person` in an assembly named `PersonInfo`. Note that the `Person` class has two constructors, one of which is parameterless.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.activator.createinstance/cs/personinfo.cs" id="Snippet1":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR_System/system.activator.createinstance/fs/personinfo.fs" id="Snippet1":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.activator.createinstance/vb/personinfo.vb" id="Snippet1":::

The following example calls the <xref:System.Activator.CreateInstance%28System.String%2CSystem.String%29> method to instantiate the `Person` class. It requires a reference to PersonInfo.dll to be added to the project. Because the <xref:System.Activator.CreateInstance%28System.String%2CSystem.String%29> method calls the `Person` class parameterless constructor, the example assigns a value to its `Name` property.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.activator.createinstance/cs/createinstanceex1.cs" id="Snippet2":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR_System/system.activator.createinstance/fs/createinstanceex1.fs" id="Snippet2":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.activator.createinstance/vb/createinstanceex1.vb" id="Snippet2":::

However, <xref:System.Activator.CreateInstance%2A> is frequently called to instantiate a type that crosses machine boundaries or that is not known at design time. In this case, you cannot include a reference to the assembly in the project and cannot make early-bound calls to the type's members. To work around this limitation, the following example uses the <xref:System.Activator.CreateInstance%2A> method along with reflection to assign a value to the `Person` object's `Name` property and to display its value.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.activator.createinstance/cs/createinstanceex1a.cs" id="Snippet3":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR_System/system.activator.createinstance/fs/createinstanceex1a.fs" id="Snippet3":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.activator.createinstance/vb/createinstanceex1a.vb" id="Snippet3":::

]]></format>
Expand Down Expand Up @@ -776,11 +781,13 @@ Note: In <see href="https://go.microsoft.com/fwlink/?LinkID=247912">.NET for Win
The following example calls the <xref:System.Activator.CreateInstance%28System.Type%2CSystem.Object%5B%5D%29> method to create a <xref:System.String> object. It calls the <xref:System.String.%23ctor%28System.Char%5B%5D%2CSystem.Int32%2CSystem.Int32%29?displayProperty=nameWithType> constructor to instantiate a string that contains ten elements from a character array starting at the fourteenth position.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.activator.createinstance/cs/CreateInstance5.cs" interactive="try-dotnet" id="Snippet5":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR_System/system.activator.createinstance/fs/CreateInstance5.fs" id="Snippet5":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.activator.createinstance/vb/CreateInstance5.vb" id="Snippet5":::

The following example creates a jagged array whose elements are arguments to be passed to a <xref:System.String> constructor. The example then passes each array to the <xref:System.Activator.CreateInstance%28System.Type%2CSystem.Object%5B%5D%29> method to invoke the appropriate string constructor.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.activator.createinstance/cs/createinstance2.cs" interactive="try-dotnet" id="Snippet4":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR_System/system.activator.createinstance/fs/createinstance2.fs" id="Snippet4":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.activator.createinstance/vb/createinstance2.vb" id="Snippet4":::

]]></format>
Expand Down Expand Up @@ -1812,6 +1819,7 @@ Note: In <see href="https://go.microsoft.com/fwlink/?LinkID=247912">.NET for Win

:::code language="cpp" source="~/samples/snippets/cpp/VS_Snippets_CLR_System/system.activation.createinstance~~1/cpp/remarks.cpp" id="Snippet1":::
:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.activation.createinstance~~1/cs/remarks.cs" id="Snippet1":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR_System/system.activation.createinstance~~1/fs/remarks.fs" id="Snippet1":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.activation.createinstance~~1/vb/remarks.vb" id="Snippet1":::

In general, there is no use for the <xref:System.Activator.CreateInstance%60%601> generic method in application code, because the type must be known at compile time. If the type is known at compile time, normal instantiation syntax can be used (`new` operator in C#, `New` in Visual Basic, `gcnew` in C++). If the type is not known at compile time, you can call a non-generic overload of <xref:System.Activator.CreateInstance%2A>.
Expand Down Expand Up @@ -1899,6 +1907,7 @@ Note: In <see href="https://go.microsoft.com/fwlink/?LinkID=247912">.NET for Win

:::code language="cpp" source="~/samples/snippets/cpp/VS_Snippets_CLR/ActivatorX/cpp/ActivatorX.cpp" id="Snippet3":::
:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR/ActivatorX/cs/ActivatorX.cs" id="Snippet3":::
:::code language="fsharp" source="~/samples/snippets/fsharp/VS_Snippets_CLR/ActivatorX/fs/ActivatorX.fs" id="Snippet3":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR/ActivatorX/VB/ActivatorX.vb" id="Snippet3":::

]]></format>
Expand Down