ResourceManager.GetObject
ResourceManager.GetObject
ResourceManager.GetObject
ResourceManager.GetObject
Method
Definition
Returns the value of the specified non-string resource for the current culture.
Overloads
GetObject(String) GetObject(String) GetObject(String) GetObject(String) |
Returns the value of the specified non-string resource. |
GetObject(String, CultureInfo) GetObject(String, CultureInfo) GetObject(String, CultureInfo) GetObject(String, CultureInfo) |
Gets the value of the specified non-string resource localized for the specified culture. |
GetObject(String) GetObject(String) GetObject(String) GetObject(String)
Returns the value of the specified non-string resource.
public:
virtual System::Object ^ GetObject(System::String ^ name);
public virtual object GetObject (string name);
abstract member GetObject : string -> obj
override this.GetObject : string -> obj
Public Overridable Function GetObject (name As String) As Object
Parameters
Returns
The value of the resource localized for the caller's current culture settings. If an appropriate resource set exists but name
cannot be found, the method returns null
.
Exceptions
The name
parameter is null
.
No usable set of localized resources has been found, and there are no default culture resources. For information about how to handle this exception, see the "Handling MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions" section in the ResourceManager class topic.
The default culture's resources reside in a satellite assembly that could not be found. For information about how to handle this exception, see the "Handling MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions" section in the ResourceManager class topic.
Examples
The following example uses the GetObject(String) method to deserialize a custom object. The example includes a source code file named UIElements.cs (UIElements.vb if you're using Visual Basic) that defines the following structure named PersonTable
. This structure is intended to be used by a general table display routine that displays the localized names of table columns. Note that the PersonTable
structure is marked with the SerializableAttribute attribute.
using System;
[Serializable] public struct PersonTable
{
public readonly int nColumns;
public readonly string column1;
public readonly string column2;
public readonly string column3;
public readonly int width1;
public readonly int width2;
public readonly int width3;
public PersonTable(string column1, string column2, string column3,
int width1, int width2, int width3)
{
this.column1 = column1;
this.column2 = column2;
this.column3 = column3;
this.width1 = width1;
this.width2 = width2;
this.width3 = width3;
this.nColumns = typeof(PersonTable).GetFields().Length / 2;
}
}
<Serializable> Public Structure PersonTable
Public ReadOnly nColumns As Integer
Public Readonly column1 As String
Public ReadOnly column2 As String
Public ReadOnly column3 As String
Public ReadOnly width1 As Integer
Public ReadOnly width2 As Integer
Public ReadOnly width3 As Integer
Public Sub New(column1 As String, column2 As String, column3 As String,
width1 As Integer, width2 As Integer, width3 As Integer)
Me.column1 = column1
Me.column2 = column2
Me.column3 = column3
Me.width1 = width1
Me.width2 = width2
Me.width3 = width3
Me.nColumns = Me.GetType().GetFields().Count \ 2
End Sub
End Structure
The following code from a file named CreateResources.cs (CreateResources.vb for Visual Basic) creates an XML resource file named UIResources.resx that stores a table title and a PersonTable
object that contains information for an app that is localized for the English language.
using System;
using System.Resources;
public class CreateResource
{
public static void Main()
{
PersonTable table = new PersonTable("Name", "Employee Number",
"Age", 30, 18, 5);
ResXResourceWriter rr = new ResXResourceWriter(@".\UIResources.resx");
rr.AddResource("TableName", "Employees of Acme Corporation");
rr.AddResource("Employees", table);
rr.Generate();
rr.Close();
}
}
Imports System.Resources
Module CreateResource
Public Sub Main()
Dim table As New PersonTable("Name", "Employee Number", "Age", 30, 18, 5)
Dim rr As New ResXResourceWriter(".\UIResources.resx")
rr.AddResource("TableName", "Employees of Acme Corporation")
rr.AddResource("Employees", table)
rr.Generate()
rr.Close()
End Sub
End Module
The following code in a source code file named GetObject.cs (GetObject.vb) then retrieves the resources and displays them to the console.
using System;
using System.Resources;
[assembly: NeutralResourcesLanguageAttribute("en")]
public class Example
{
public static void Main()
{
string fmtString = String.Empty;
ResourceManager rm = new ResourceManager("UIResources", typeof(Example).Assembly);
string title = rm.GetString("TableName");
PersonTable tableInfo = (PersonTable) rm.GetObject("Employees");
if (! String.IsNullOrEmpty(title)) {
fmtString = "{0," + ((Console.WindowWidth + title.Length) / 2).ToString() + "}";
Console.WriteLine(fmtString, title);
Console.WriteLine();
}
for (int ctr = 1; ctr <= tableInfo.nColumns; ctr++) {
string columnName = "column" + ctr.ToString();
string widthName = "width" + ctr.ToString();
string value = tableInfo.GetType().GetField(columnName).GetValue(tableInfo).ToString();
int width = (int) tableInfo.GetType().GetField(widthName).GetValue(tableInfo);
fmtString = "{0,-" + width.ToString() + "}";
Console.Write(fmtString, value);
}
Console.WriteLine();
}
}
Imports System.Resources
<Assembly: NeutralResourcesLanguageAttribute("en")>
Module Example
Public Sub Main()
Dim fmtString As String = String.Empty
Dim rm As New ResourceManager("UIResources", GetType(Example).Assembly)
Dim title As String = rm.GetString("TableName")
Dim tableInfo As PersonTable = DirectCast(rm.GetObject("Employees"), PersonTable)
If Not String.IsNullOrEmpty(title) Then
fmtString = "{0," + ((Console.WindowWidth + title.Length) \ 2).ToString() + "}"
Console.WriteLine(fmtString, title)
Console.WriteLine()
End If
For ctr As Integer = 1 To tableInfo.nColumns
Dim columnName As String = "column" + ctr.ToString()
Dim widthName As String = "width" + ctr.ToString()
Dim value As String = CStr(tableInfo.GetType().GetField(columnName).GetValue(tableInfo))
Dim width As Integer = CInt(tableInfo.GetType().GetField(widthName).GetValue(tableInfo))
fmtString = "{0,-" + width.ToString() + "}"
Console.Write(fmtString, value)
Next
Console.WriteLine()
End Sub
End Module
You can build the necessary resource file and assemblies and run the app by executing the following batch file. You must use the /r
option to supply Resgen.exe with a reference to UIElements.dll so that it can access information about the PersonTable
structure. If you're using C#, replace the vbc
compiler name with csc
, and replace the .vb
extension with .cs
.
vbc /t:library UIElements.vb
vbc CreateResources.vb /r:UIElements.dll
CreateResources
resgen UIResources.resx /r:UIElements.dll
vbc GetObject.vb /r:UIElements.dll /resource:UIResources.resources
GetObject.exe
Remarks
The GetObject method is used to retrieve non-string resources. These include values that belong to primitive data types such as Int32 or Double, bitmaps (such as a System.Drawing.Bitmap object), or custom serialized objects. Typically, the returned object must be cast (in C#) or converted (in Visual Basic) to an object of the appropriate type.
The returned resource is localized for the UI culture of the current thread, which is defined by the CultureInfo.CurrentUICulture property. If the resource is not localized for that culture, the resource manager uses fallback rules to load an appropriate resource. If no usable set of localized resources is found, the ResourceManager falls back on the default culture's resources. If a resource set for the default culture is not found, the method throws a MissingManifestResourceException exception or, if the resource set is expected to reside in a satellite assembly, a MissingSatelliteAssemblyException exception. If the resource manager can load an appropriate resource set but cannot find a resource named name
, the method returns null
.
The IgnoreCase property determines whether the comparison of name
with the names of resources is case-insensitive (the default) or case-sensitive.
Caution
This method can throw more exceptions than are listed. One reason this might occur is if a method that this method calls throws an exception. For example, a FileLoadException exception might be thrown if an error was made deploying or installing a satellite assembly, or a SerializationException exception might be thrown if a user-defined type throws a user-defined exception when the type is deserialized.
Performance Considerations
If you call the GetObject method multiple times with the same name
parameter, do not depend on the method returning a reference to the same object with each call. This is because the GetObject method can return a reference to an existing resource object in a cache, or it can reload the resource and return a reference to a new resource object.
Security
ReflectionPermission
when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Associated enumeration: MemberAccess.
- See also
GetObject(String, CultureInfo) GetObject(String, CultureInfo) GetObject(String, CultureInfo) GetObject(String, CultureInfo)
Gets the value of the specified non-string resource localized for the specified culture.
public:
virtual System::Object ^ GetObject(System::String ^ name, System::Globalization::CultureInfo ^ culture);
public virtual object GetObject (string name, System.Globalization.CultureInfo culture);
abstract member GetObject : string * System.Globalization.CultureInfo -> obj
override this.GetObject : string * System.Globalization.CultureInfo -> obj
Public Overridable Function GetObject (name As String, culture As CultureInfo) As Object
Parameters
- culture
- CultureInfo CultureInfo CultureInfo CultureInfo
The culture for which the resource is localized. If the resource is not localized for this culture, the resource manager uses fallback rules to locate an appropriate resource.
If this value is null
, the CultureInfo object is obtained by using the CurrentUICulture property.
Returns
The value of the resource, localized for the specified culture. If an appropriate resource set exists but name
cannot be found, the method returns null
.
Exceptions
The name
parameter is null
.
No usable set of resources have been found, and there are no default culture resources. For information about how to handle this exception, see the "Handling MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions" section in the ResourceManager class topic.
The default culture's resources reside in a satellite assembly that could not be found. For information about how to handle this exception, see the "Handling MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions" section in the ResourceManager class topic.
Examples
The following example uses the GetObject(String, CultureInfo) method to deserialize a custom object. The example includes a source code file named NumberInfo.cs (NumberInfo.vb if you're using Visual Basic) that defines the following structure named Numbers
. This structure is intended to be used by a simple educational app that teaches non-English speaking students to count to ten in English. Note that the Numbers
class is marked with the SerializableAttribute attribute.
using System;
[Serializable] public class Numbers
{
public readonly string One;
public readonly string Two;
public readonly string Three;
public readonly string Four;
public readonly string Five;
public readonly string Six;
public readonly string Seven;
public readonly string Eight;
public readonly string Nine;
public readonly string Ten;
public Numbers(string one, string two, string three, string four,
string five, string six, string seven, string eight,
string nine, string ten)
{
this.One = one;
this.Two = two;
this.Three = three;
this.Four = four;
this.Five = five;
this.Six = six;
this.Seven = seven;
this.Eight = eight;
this.Nine = nine;
this.Ten = ten;
}
}
<Serializable> Public Class Numbers
Public Readonly One As String
Public ReadOnly Two As String
Public ReadOnly Three As String
Public ReadOnly Four As String
Public ReadOnly Five As String
Public ReadOnly Six As String
Public ReadOnly Seven As String
Public ReadOnly Eight As String
Public ReadOnly Nine As String
Public ReadOnly Ten As String
Public Sub New(one As String, two As String, three As String, four As String,
five As String, six As String, seven As String, eight As String,
nine As String, ten As String)
Me.One = one
Me.Two = two
Me.Three = three
Me.Four = four
Me.Five = five
Me.Six = six
Me.Seven = seven
Me.Eight = eight
Me.Nine = nine
Me.Ten = ten
End Sub
End Class
The following source code from a file named CreateResources.cs (CreateResources.vb for Visual Basic) creates XML resource files for the default English language, as well as for the French, Portuguese, and Russian languages.
using System;
using System.Resources;
public class CreateResource
{
public static void Main()
{
Numbers en = new Numbers("one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten");
CreateResourceFile(en, "en");
Numbers fr = new Numbers("un", "deux", "trois", "quatre", "cinq",
"six", "sept", "huit", "neuf", "dix");
CreateResourceFile(fr, "fr");
Numbers pt = new Numbers("um", "dois", "três", "quatro", "cinco",
"seis", "sete", "oito", "nove", "dez");
CreateResourceFile(pt, "pt");
Numbers ru = new Numbers("один", "два", "три", "четыре", "пять",
"шесть", "семь", "восемь", "девять", "десять");
CreateResourceFile(ru, "ru");
}
public static void CreateResourceFile(Numbers n, string lang)
{
string filename = @".\NumberResources" +
(lang != "en" ? "." + lang : "" ) +
".resx";
ResXResourceWriter rr = new ResXResourceWriter(filename);
rr.AddResource("Numbers", n);
rr.Generate();
rr.Close();
}
}
Imports System.Resources
Module CreateResource
Public Sub Main()
Dim en As New Numbers("one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten")
CreateResourceFile(en, "en")
Dim fr As New Numbers("un", "deux", "trois", "quatre", "cinq",
"six", "sept", "huit", "neuf", "dix")
CreateResourceFile(fr, "fr")
Dim pt As New Numbers("um", "dois", "três", "quatro", "cinco",
"seis", "sete", "oito", "nove", "dez")
CreateResourceFile(pt, "pt")
Dim ru As New Numbers("один", "два", "три", "четыре", "пять",
"шесть", "семь", "восемь", "девять", "десять")
CreateResourceFile(ru, "ru")
End Sub
Public Sub CreateResourceFile(n As Numbers, lang As String)
Dim filename As String = ".\NumberResources" +
If(lang <> "en", "." + lang, "") +
".resx"
Dim rr As New ResXResourceWriter(filename)
rr.AddResource("Numbers", n)
rr.Generate()
rr.Close()
End Sub
End Module
The resources are consumed by the following app, which sets the current UI culture to French (France), Portuguese (Brazil), or Russian (Russia). It calls the GetObject(String) method to get a Numbers
object that contains localized numbers and the GetObject(String, CultureInfo) method to get a Numbers
object that contains English language numbers. It then displays odd numbers using the current UI culture and the English language. The source code file is named ShowNumbers.cs (ShowNumbers.vb).
using System;
using System.Globalization;
using System.Resources;
using System.Threading;
[assembly:NeutralResourcesLanguageAttribute("en-US")]
public class Example
{
static string[] cultureNames = { "fr-FR", "pt-BR", "ru-RU" };
public static void Main()
{
// Make any non-default culture the current culture.
Random rnd = new Random();
CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureNames[rnd.Next(0, cultureNames.Length)]);
Thread.CurrentThread.CurrentUICulture = culture;
Console.WriteLine("The current culture is {0}\n", CultureInfo.CurrentUICulture.Name);
CultureInfo enCulture = CultureInfo.CreateSpecificCulture("en-US");
ResourceManager rm = new ResourceManager(typeof(NumberResources));
Numbers numbers = (Numbers) rm.GetObject("Numbers");
Numbers numbersEn = (Numbers) rm.GetObject("Numbers", enCulture);
Console.WriteLine("{0} --> {1}", numbers.One, numbersEn.One);
Console.WriteLine("{0} --> {1}", numbers.Three, numbersEn.Three);
Console.WriteLine("{0} --> {1}", numbers.Five, numbersEn.Five);
Console.WriteLine("{0} --> {1}", numbers.Seven, numbersEn.Seven);
Console.WriteLine("{0} --> {1}\n", numbers.Nine, numbersEn.Nine);
}
}
internal class NumberResources
{
}
// The example displays output like the following:
// The current culture is pt-BR
//
// um --> one
// três --> three
// cinco --> five
// sete --> seven
// nove --> nine
Imports System.Globalization
Imports System.Resources
Imports System.Threading
<assembly:NeutralResourcesLanguageAttribute("en-US")>
Module Example
Dim cultureNames() As String = { "fr-FR", "pt-BR", "ru-RU" }
Public Sub Main()
' Make any non-default culture the current culture.
Dim rnd As New Random
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(cultureNames(rnd.Next(0, cultureNames.Length)))
Thread.CurrentThread.CurrentUICulture = culture
Console.WriteLine("The current culture is {0}", CultureInfo.CurrentUICulture.Name)
Console.WriteLine()
Dim enCulture As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
Dim rm As New ResourceManager(GetType(NumberResources))
Dim numbers As Numbers = CType(rm.GetObject("Numbers"), Numbers)
Dim numbersEn As Numbers = CType(rm.GetObject("Numbers", enCulture), Numbers)
Console.WriteLine("{0} --> {1}", numbers.One, numbersEn.One)
Console.WriteLine("{0} --> {1}", numbers.Three, numbersEn.Three)
Console.WriteLine("{0} --> {1}", numbers.Five, numbersEn.Five)
Console.WriteLine("{0} --> {1}", numbers.Seven, numbersEn.Seven)
Console.WriteLine("{0} --> {1}", numbers.Nine, numbersEn.Nine)
Console.WriteLine()
End Sub
End Module
Friend Class NumberResources
End Class
' The example displays output like the following:
' The current culture is pt-BR
'
' um --> one
' três --> three
' cinco --> five
' sete --> seven
' nove --> nine
You can use the following batch file to build and execute the Visual Basic version of the example. If you're using C#, replace vbc
with csc
, and replace the .vb
extension with .cs
.
vbc /t:library NumberInfo.vb
vbc CreateResources.vb /r:NumberInfo.dll
CreateResources
resgen NumberResources.resx /r:NumberInfo.dll
resgen NumberResources.fr.resx /r:Numberinfo.dll
Md fr
al /embed:NumberResources.fr.resources /culture:fr /t:lib /out:fr\ShowNumbers.resources.dll
resgen NumberResources.pt.resx /r:Numberinfo.dll
Md pt
al /embed:NumberResources.pt.resources /culture:pt /t:lib /out:pt\ShowNumbers.resources.dll
resgen NumberResources.ru.resx /r:Numberinfo.dll
Md ru
al /embed:NumberResources.ru.resources /culture:ru /t:lib /out:ru\ShowNumbers.resources.dll
vbc ShowNumbers.vb /r:NumberInfo.dll /resource:NumberResources.resources
ShowNumbers.exe
Remarks
The GetObject(String, CultureInfo) method is used to retrieve non-string resources. These include values that belong to primitive data types such as Int32 or Double, bitmaps (such as a System.Drawing.Bitmap object), or custom serialized objects. Typically, the returned object must be cast (in C#) or converted (in Visual Basic) to an object of the appropriate type.
The returned resource is localized for the culture that is specified by culture
, or for the culture that is specified by the CultureInfo.CurrentUICulture property if culture
is null
. If the resource is not localized for that culture, the resource manager uses fallback rules to load an appropriate resource. If no usable set of localized resources is found, the resource manager falls back on the default culture's resources. If a resource set for the default culture is not found, the method throws a MissingManifestResourceException exception or, if the resource set is expected to reside in a satellite assembly, a MissingSatelliteAssemblyException exception. If the resource manager can load an appropriate resource set but cannot find a resource named name
, the method returns null
.
The IgnoreCase property determines whether the comparison of name
with the names of resources is case-insensitive (the default) or case-sensitive.
Caution
This method can throw more exceptions than are listed. One reason this might occur is if a method that this method calls throws an exception. For example, a FileLoadException exception might be thrown if an error was made deploying or installing a satellite assembly, or a SerializationException exception might be thrown if a user-defined type throws a user-defined exception when the type is deserialized.
Performance Considerations
If you call the GetObject method multiple times with the same name
parameter, do not depend on the method returning a reference to the same object with each call. This is because the GetObject method can return a reference to an existing resource object in a cache, or it can reload the resource and return a reference to a new resource object.
Security
ReflectionPermission
when invoked late-bound through mechanisms such as InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]). Associated enumeration: MemberAccess.
- See also
Applies to
Feedback
We'd love to hear your thoughts. Choose the type you'd like to provide:
Our feedback system is built on GitHub Issues. Read more on our blog.
Loading feedback...