Error cs0118 editor is a namespace but is used like a type

My program uses a class called Time2. I have the reference added to TimeTest but I keep getting the error, 'Time2' is a 'namespace' but is used like a 'type'. Could someone please tell me what this...

My program uses a class called Time2. I have the reference added to TimeTest but I keep getting the error, 'Time2' is a 'namespace' but is used like a 'type'.

Could someone please tell me what this error is and how to fix it?

    namespace TimeTest
    {
      class TimeTest
      {
        static void Main(string[] args)
        {
            Time2 t1 = new Time2();
        }
      }
    }

Nikkkshit's user avatar

Nikkkshit

2,0252 gold badges8 silver badges19 bronze badges

asked Feb 21, 2013 at 16:45

TheAce's user avatar

4

I suspect you’ve got the same problem at least twice.

Here:

    namespace TimeTest
    {
        class TimeTest
        {
    }

… you’re declaring a type with the same name as the namespace it’s in. Don’t do that.

Now you apparently have the same problem with Time2. I suspect if you add:

    using Time2;

to your list of using directives, your code will compile. But please, please, please fix the bigger problem: the problematic choice of names. (Follow the link above to find out more details of why it’s a bad idea.)

(Additionally, unless you’re really interested in writing time-based types, I’d advise you not to do so… and I say that as someone who does do exactly that. Use the built-in capabilities, or a third party library such as, um, mine. Working with dates and times correctly is surprisingly hairy. :)

Nikkkshit's user avatar

Nikkkshit

2,0252 gold badges8 silver badges19 bronze badges

answered Feb 21, 2013 at 16:49

Jon Skeet's user avatar

Jon SkeetJon Skeet

1.4m851 gold badges9045 silver badges9133 bronze badges

8

namespace TestApplication // Remove .Controller
{
    public class HomeController : Controller
    {
       public ActionResult Index()
        {
            return View();
        }
    }
}

Remove the controller word from namepsace

Danh's user avatar

Danh

5,8167 gold badges29 silver badges43 bronze badges

answered Nov 17, 2016 at 1:44

shoba's user avatar

shobashoba

2412 silver badges2 bronze badges

4

The class TimeTest is conflicting with namespace TimeTest.

If you can’t change the namespace and the class name:

Create an alias for the class type.

using TimeTest_t = TimeTest.TimeTest;

TimeTest_t s = new TimeTest_t();

answered Mar 17, 2021 at 14:11

Mats Gausdal's user avatar

All the answers indicate the cause, but sometimes the bigger problem is identifying all the places that define an improper namespace. With tools like Resharper that automatically adjust the namespace using the folder structure, it is rather easy to encounter this issue.

You can get all the lines that create the issue by searching in project / solution using the following regex:

namespace .+.TheNameUsedAsBothNamespaceAndType

answered Oct 3, 2020 at 7:57

Alexei - check Codidact's user avatar

If you’re working on a big app and can’t change any names, you can type a . to select the type you want from the namespace:

namespace Company.Core.Context{
  public partial class Context : Database Context {
    ...
  }
}
...

using Company.Core.Context;
someFunction(){
 var c = new Context.Context();
}

answered Jun 8, 2020 at 22:24

James L.'s user avatar

James L.James L.

11.8k4 gold badges45 silver badges59 bronze badges

I had this problem as I created a class «Response.cs» inside a folder named «Response». So VS was catching the new Response () as Folder/namespace.

So I changed the class name to StatusResponse.cs and called new StatusResponse().This solved the issue.

answered Sep 30, 2020 at 3:46

Ani's user avatar

AniAni

3812 silver badges7 bronze badges

If you are here for EF Core related issues, here’s the tip:

Name your Migration’s subfolder differently than the Database Context’s name.

This will solve it for you.

My error was something like this:
ModelSnapshot.cs error CS0118: Context is a namespace but is used like a type

answered Jan 5, 2022 at 20:16

Andrei Iovan's user avatar

Please check that your class and namespace name is the same…

It happens when the namespace and class name are the same.
do one thing write the full name of the namespace when you want to use the namespace.

using Student.Models.Db;

namespace Student.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            List<Student> student = null;
            return View();
        }
    }

Cloud Ace Wenyuan Jiang's user avatar

answered May 24, 2019 at 2:32

Muhammad Usama Arshad's user avatar

if the error is

Line 26:
Line 27: @foreach (Customers customer in Model)
Line 28: {
Line 29:

give the full name space
like
@foreach (Start.Models.customer customer in Model)

answered Dec 9, 2019 at 9:58

Nelcon Croos's user avatar

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0118

Compiler Error CS0118

07/20/2015

CS0118

CS0118

9a612432-6e56-4e9b-9d8c-7d7b43f58c1a

Compiler Error CS0118

‘construct1_name’ is a ‘construct1’ but is used like a ‘construct2’

The compiler detected a situation in which a construct was used in some erroneous way or a disallowed operation was tried on a construct. Some common examples include the following:

  • A try to instantiate a namespace (instead of a class)

  • A try to call a field (instead of a method)

  • A try to use a type as a variable

  • A try to use an extern alias as a type.

To resolve this error, make sure that the operation you are performing is valid for the type you are performing the operation on.

Example

The following sample generates CS0118.

// CS0118.cs  
// compile with: /target:library  
namespace MyNamespace  
{  
   class MyClass  
   {  
      // MyNamespace not a class  
      MyNamespace ix = new MyNamespace ();   // CS0118  
   }  
}  

  • Remove From My Forums
  • Question

  • I defined a class in Microsoft.Practices namespace in my project, which
    referecs System.Xml.Linq.dll and System.Windows.Interactivity.dll files.

    When using Expression class in System.Linq.Expressions namespace, the
    project compile failure whith error message:
    error CS0118: ‘Microsoft.Expression’ is a ‘namespace’ but is used like a ‘type’

    System.Windows.Interactivity.dll contains Microsoft.Expression.BlendSDK namespace,
    which not used in my class, using alias can avoid this error. Microsoft.Practices
    namespace conflicts with Microsoft.Expression.BlendSDK namespace. Does the compiler
    search all *.dll files for a class to check namespace even not using that dll?

    Is this a compiler bug? Or I missunderstand the compiler.

    Thanks.

    using System;
    using System.Linq.Expressions;
    //using EXP=System.Linq.Expressions.Expression;
    
    namespace Microsoft.Practices
    {
        class Program
        {
            static void Main(string[] args)
            {
                
            }
    
            //private static void ExpressionForm(EXP expression)
            private static void ExpressionForm(Expression expression)
            {
                if (expression.NodeType != ExpressionType.Call)
                {
                    throw new InvalidOperationException("Invalid expression form passed");
                }
            }
        }
    }

    • Edited by

      Saturday, November 30, 2013 12:04 AM

Answers

  • Hi. There is a naming clash between the System.Linq.Expressions.Expression class and System.Windows.Interactivity.Expression namespace. To get round it using an alias you can fully reference the Expression class:

    private static void ExpressionForm(System.Linq.Expressions.Expression expression)
    {
      ...
    }

    There are other options for using an alias with the System.Windows.Interactivity reference but I wouldn’t go down that route as it may create problems using classes from the assembly in XAML (I know it’s a console app but I’m assuming your going
    to be using WPF if you want to use System.Windows.Interactivity).

    • Marked as answer by
      Eason_H
      Monday, December 9, 2013 1:38 AM

  • Hi Lin,

    To resolve this error, make sure that the operation you are performing is valid for the type you are performing the operation on.

    The compiler detected a situation in which a construct was used in some erroneous way or a disallowed operation was tried on a construct. Some common examples include the following:

    • A try to instantiate a namespace (instead of a class)

    • A try to call a field (instead of a method)

    • A try to use a type as a variable

    • A try to use an extern alias as a type.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.

    Click
    HERE to participate the survey.

    • Marked as answer by
      Eason_H
      Monday, December 9, 2013 1:38 AM

C# Compiler Error

CS0118 – construct1_name’ is a ‘construct1’ but is used like a ‘construct2’

Reason for the Error

You will receive this error when you perform a disallowed operation on a construct. For example, the namespaces in C# cannot be instantiated but what happens when you try to instantiate an namespace? You will receive the compiler error CS0118 in C#.

Below is a code snippet demonstrating this error.

namespace DeveloperPublishNamespace
{
    public class Class1
    {
        public int MyProperty { get; set; }
    }

    public class DeveloperPublish
    {
        public static void Main()
        {
            DeveloperPublishNamespace obj = new DeveloperPublishNamespace();
        }
    }
}

Error CS0118 ‘DeveloperPublishNamespace’ is a namespace but is used like a type ConsoleApp1 C:UsersSenthilsourcereposConsoleApp1ConsoleApp1Program.cs 12 Active

C# Error CS0118 – construct1_name' is a 'construct1' but is used like a 'construct2'

Solution

To fix the error code CS0118, ensure that the operation that you are performing is valid for the type that you are using. For example, use the class instead of the namespace for the above example.

Annchousinka

0 / 0 / 0

Регистрация: 03.10.2013

Сообщений: 5

1

03.10.2013, 10:24. Показов 9690. Ответов 6

Метки нет (Все метки)


Всем привет.Пишу WebPart для SharePoint, пытаюсь сделать TreeView для списка.Мне выдает ошибку
1) «TreeView» является «пространство имен», но используется как «тип»
Хотя до этого писала и такой ошибки не появлялось, т.к. TreeView treeView; относится к классу System.Web.UI.WebControls
в чем может быть проблема?

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.IO;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
 
namespace TreeView.HelpDesk.VisualWebPart1
{
   [Guid("65f8b876-fbfd-4d50-942a-fe8ab317899c")]
    public class WebPart1 : System.Web.UI.WebControls.WebParts.WebPart
    {
        TreeView treeView;     //На эту часть кода ругается
        TreeNode rootNode;
       public WebPart1()
        {
              }
     protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
            // render the control
            base.RenderContents(writer);
        }
 
        protected override void CreateChildControls()
         {
             
            base.CreateChildControls();
 
            // get the current site
            SPSite currentSite = SPContext.Current.Site;
            using (SPWeb currentWeb = currentSite.OpenWeb())
            {
                // set the tree view properties
                treeView = new System.Web.UI.WebControls.TreeView();
                treeView.ShowLines = true; // show lines
                treeView.ExpandDepth = 0; // expand non
 
                SPList list = currentWeb.Lists["Service_List_Test"];
 
                // build the tree
                rootNode = new System.Web.UI.WebControls.TreeNode(list.Title, "",
                           "", list.RootFolder.ServerRelativeUrl.ToString(), "");
 
                // loop down the tree
                GetFolder(list.RootFolder, rootNode, list);
 
                // add the root node to tree view
                treeView.Nodes.Add(rootNode);
            }
            this.Controls.Add(treeView);
            base.CreateChildControls();
        }
 
        public void GetFolder(SPFolder folder, TreeNode rootNode, SPList list)
        {
            // create a new node
            TreeNode newNode = new System.Web.UI.WebControls.TreeNode(folder.Name, "",
                               "~/_layouts/images/itdl.gif",
                               folder.ServerRelativeUrl.ToString(), "");
            try
            {
                // don't add the forms folder
                if (folder.Name != "Link")
                {
                    // loop through all child folders
                    foreach (SPFolder childFolder in folder.SubFolders)
                    {
                        // don't add the forms folder
                        if (childFolder.Name != "Link")
                        {
                            TreeNode trn =
                              new System.Web.UI.WebControls.TreeNode(childFolder.Name, "",
                              "", childFolder.ServerRelativeUrl.ToString(), "");
                            newNode = GetItems(childFolder, trn);
 
                            // add the new node to the tree
                            rootNode.ChildNodes.Add(newNode);
                        }
                    }
                }
            }
            catch { }
        }
 
        public TreeNode GetItems(SPFolder folder, TreeNode node)
        {
            //Get Items from childFolder
            SPQuery qry = new SPQuery();
            qry.Folder = folder;
            SPWeb web = null;
 
            web = folder.ParentWeb;
            SPListItemCollection ic = web.Lists[folder.ParentListId].GetItems(qry);
 
            foreach (SPListItem subitem in ic)
            {
                if (subitem.Folder != null) //Is Subfolder
                {
                    // create a new node for a subfolder and add items to it
                    TreeNode childNode =
                      new System.Web.UI.WebControls.TreeNode(subitem.Folder.Name);
                    node.ChildNodes.Add(GetItems(subitem.Folder, childNode));
                }
 
                if (subitem.Folder == null)
                {
                    TreeNode trn1 = new System.Web.UI.WebControls.TreeNode(
                                          subitem["Title0"].ToString());
                    node.ChildNodes.Add(trn1);
                }
            }
            return node;
        }
    }
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Master of Orion

Эксперт .NET

6094 / 4950 / 905

Регистрация: 10.07.2011

Сообщений: 14,522

Записей в блоге: 5

03.10.2013, 10:28

2

Annchousinka, в том, что вы называете неймспейсы так же, как и классы?…



0



0 / 0 / 0

Регистрация: 03.10.2013

Сообщений: 5

03.10.2013, 10:32

 [ТС]

3

Нет namespace это никакой роли не играет, я уже меняла имя и результат такой же(((



0



Psilon

Master of Orion

Эксперт .NET

6094 / 4950 / 905

Регистрация: 10.07.2011

Сообщений: 14,522

Записей в блоге: 5

03.10.2013, 10:38

4

да ну, не влияет?

C#
1
2
3
4
5
6
7
namespace TreeView2.HelpDesk.VisualWebPart1
{
    [Guid("65f8b876-fbfd-4d50-942a-fe8ab317899c")]
    public class WebPart1 : System.Web.UI.WebControls.WebParts.WebPart
    {
        TreeView treeView; //На эту часть кода ругается
        TreeNode rootNode;

внезапно заработало.



0



0 / 0 / 0

Регистрация: 03.10.2013

Сообщений: 5

03.10.2013, 10:52

 [ТС]

5

а у меня нет)пересоздала проект и заработало
Спасибо за помощь все равно

«

Добавлено через 1 минуту
У меня теперь другая ошибка, когда я разворачиваю WebPart пишет следующее:
«Ошибка в шаге развертывания «Повторное использование пула приложений IIS»: Сервер недоступен. Следует убедиться, что сервер выполняется и подключен к ферме SharePoint.



0



Master of Orion

Эксперт .NET

6094 / 4950 / 905

Регистрация: 10.07.2011

Сообщений: 14,522

Записей в блоге: 5

03.10.2013, 12:03

6

Annchousinka, iisreset попробуй. В командной строке.

Ну или зайди в IIS и убедись, что там все запущено.



0



0 / 0 / 0

Регистрация: 03.10.2013

Сообщений: 5

03.10.2013, 12:49

 [ТС]

7

Спасибо за ответ)
Я проверила в IIS в Aplication Pools все было остановлено, я сделала iisreset все запустилось кроме одного последнего «SharePoint Web Services Root»
перезапустила приложение и все равно эта же ошибка((



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

03.10.2013, 12:49

Помогаю со студенческими работами здесь

Ошибка CS0234 Тип или имя пространства имен «Interpor» не существует в пространстве имен «Microsoft.Office»
Выбивает &quot;Ошибка CS0234 Тип или имя пространства имен &quot;Interpor&quot; не существует в пространстве имен…

Известны сорта роз, выращиваемых тремя цветоводами: «Анжелика», «Виктория», «Гагарин», «Ave Maria», «Катарина», «Юбилейн
Известны сорта роз, выращиваемых тремя цветоводами: &quot;Анжелика&quot;, &quot;Виктория&quot;, &quot;Гагарин&quot;, &quot;Ave…

Методом вычислить тип треугольника: «не существует», «тупоугольный», «прямоугольный», «остроугольный»
Помогите пожалуйста
С помощью метода вычислить тип треугольника::cry:
1) если первый параметр…

Является «поле», но используется как «тип». Как исправить?
является &quot;поле&quot;, но используется как &quot;тип&quot; как исправить?

double findRoot(double(*f)(double),…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

7

I am getting 2 errors in my c# script.

  1. AssetsscriptsplayerMovement.cs(8,5): error CS0118: 'PlayerControls' is a namespace but is used like a type
  2. AssetsscriptsplayerMovement.cs(4,19): error CS0234: The type or namespace name 'InputSystem' does not exist in the namespace 'UnityEngine' (are you missing an assembly reference?)

playerMovement.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class playerMovement : MonoBehaviour
{
    PlayerControls controls;
    Vector2 move;
    void Awake()
    {
        controls = new PlayerControls();

        controls.Gameplay.move.performed += ctx => move = ctx.ReadValue<Vector2>();
        controls.Gameplay.move.canceled += ctx => move = Vector2.zero;
    }
    void Update()
    {
        Vector2 m = new Vector2(move.x, move.y) * Time.deltaTime;
        transform.Translate(m, Space.World);
    }
}

I am using the new Input System 0.2.1 in unity 2018.4.25f.

The PlayerControls script is auto-generated from an Actions Input object, and it is in the main root «Assets».

#c# #.net

Вопрос:

 namespace Vectigal.Invoice.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class InvoicesController : ControllerBase
    {
        private readonly InvoiceContext _context;

        public InvoicesController(InvoiceContext context)
        {
            _context = context;
        }

        // GET: api/Invoices
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Invoice>>> GetInvoices()
        {
            return await _context.Invoices.ToListAsync();
        }
 

Я получаю сообщение об ошибке, когда пытаюсь запустить этот проект dotnet.
Что я делаю не так?

Комментарии:

1. Когда вы задаете подобный вопрос, пожалуйста, укажите, в какой строке есть ошибка (если дважды щелкнуть по ошибке, VS перейдет к нарушающей строке). Таким образом, люди смогут быстро найти проблему без необходимости компилировать ваш код у себя в голове.

2. Пожалуйста, проясните вашу конкретную проблему или предоставьте дополнительные сведения, чтобы точно указать, что вам нужно. Поскольку это написано в настоящее время, трудно точно сказать, о чем вы просите.

Ответ №1:

Это связано Invoice с тем, что это пространство имен ( Vectigal.Invoice ), а не тип — именно то, о чем говорится в ошибке.

IEnumerable<Invoice> является уродливым. Вы объявили что-то еще, называемое Invoice где-то в другом месте? Если это так, либо измените его имя, либо измените имя пространства имен, чтобы они не сталкивались. Не называйте две разные вещи одним и тем же именем.

Вы всегда можете полностью указать имя, в качестве альтернативы, т. Е. : IEnumerable<SomeOtherNamespace.Invoice> , но это становится немного многословным.

Понравилась статья? Поделить с друзьями:
  • Error cs0117 time does not contain a definition for deltatime
  • Error cs0117 random does not contain a definition for range
  • Error cs0117 physics2d does not contain a definition for overlapcircleall
  • Error cs0117 input does not contain a definition for getaxis
  • Error cs0117 input does not contain a definition for get key