diff --git a/docs/csharp/misc/cs0119.md b/docs/csharp/misc/cs0119.md index 2292054412a43..1d7558da70bf6 100644 --- a/docs/csharp/misc/cs0119.md +++ b/docs/csharp/misc/cs0119.md @@ -20,7 +20,9 @@ ms.assetid: 048924f1-378f-4021-bd20-299d3218f810 - A method identifier is used as if it were a struct or class -## Example +## Examples + +### Example 1 The following sample generates CS0119: 'C.B()' is a method, which is not valid in the given context. You can fix this error by changing the name of the method `C.B`, or using the fully qualified name for the class `B` like `N2.B`. @@ -42,3 +44,70 @@ namespace N1 } } ``` + +### Example 2 + +The following sample shows a common scenario where CS0119 occurs when trying to add class names to a collection of types. The compiler expects instances, not class names. + +```csharp +using System; +using System.Collections.Generic; + +public class Page_BaseClass { } +public class Page_CRTable { } +public class Page_DBGridWithTools { } + +public static class PageTypeManager +{ + public static List GetPageTypes() + { + List pageTypesList = new List(); + + // CS0119: 'Page_BaseClass' is a type, which is not valid in the given context + pageTypesList.Add(Page_BaseClass); + pageTypesList.Add(Page_CRTable); + pageTypesList.Add(Page_DBGridWithTools); + + return pageTypesList; + } +} +``` + +To fix this error, use the method or the `typeof` operator to get `Type` instances: + +```csharp +using System; +using System.Collections.Generic; + +public static class PageTypeManager +{ + public static List GetPageTypes() + { + List pageTypesList = new List(); + + // Use typeof operator to get Type instances + pageTypesList.Add(typeof(Page_BaseClass)); + pageTypesList.Add(typeof(Page_CRTable)); + pageTypesList.Add(typeof(Page_DBGridWithTools)); + + return pageTypesList; + } + + // Alternative: Load types dynamically by name + public static List GetPageTypesByName(string[] typeNames) + { + List pageTypesList = new List(); + + foreach (string typeName in typeNames) + { + Type type = Type.GetType(typeName); + if (type != null) + { + pageTypesList.Add(type); + } + } + + return pageTypesList; + } +} +```