Edit

Share via


Compiler Error CS0119

'construct1_name' is a 'construct1', which is not valid in the given context.

The compiler detected an unexpected construct such as the following:

  • A class constructor is not a valid test expression in a conditional statement.

  • A class name was used instead of an instance name to refer to an array element.

  • A method identifier is used as if it were a struct or class

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.

namespace N2
{
    public static class B
    {
        public static void X() {}
    }
}

namespace N1
{
    public class C
    {
        void B() {}
        void M() => B.X();   // CS0119
    }
}

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 Type instances, not class names.

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<Type> GetPageTypes()
    {
        List<Type> pageTypesList = new List<Type>();
        
        // 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 Type.GetType method or the typeof operator to get Type instances:

using System;
using System.Collections.Generic;

public static class PageTypeManager
{
    public static List<Type> GetPageTypes()
    {
        List<Type> pageTypesList = new List<Type>();
        
        // 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<Type> GetPageTypesByName(string[] typeNames)
    {
        List<Type> pageTypesList = new List<Type>();
        
        foreach (string typeName in typeNames)
        {
            Type type = Type.GetType(typeName);
            if (type != null)
            {
                pageTypesList.Add(type);
            }
        }
        
        return pageTypesList;
    }
}