Ошибка компилятора cs0266

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0266

Compiler Error CS0266

07/20/2015

CS0266

CS0266

6cca5d6a-f3e0-482a-af25-af73bfe3e303

Compiler Error CS0266

Cannot implicitly convert type ‘type1’ to ‘type2’. An explicit conversion exists (are you missing a cast?)

This error occurs when your code tries to convert between two types that cannot be implicitly converted, but where an explicit conversion is available. For more information, see Casting and Type Conversions.

The following code shows examples that generate CS0266:

// CS0266.cs
class MyClass
{
    public static void Main()
    {
        // You cannot implicitly convert a double to an integer.
        double d = 3.2;

        // The following line causes compiler error CS0266.
        int i1 = d;

        // However, you can resolve the error by using an explicit conversion.
        int i2 = (int)d;  

        // You cannot implicitly convert an object to a class type.
        object obj = new MyClass();

        // The following assignment statement causes error CS0266.
        MyClass myClass = obj;

        // You can resolve the error by using an explicit conversion.
        MyClass c = (MyClass)obj;

        // You cannot implicitly convert a base class object to a derived class type.
        MyClass mc = new MyClass();
        DerivedClass dc = new DerivedClass();

        // The following line causes compiler error CS0266.
        dc = mc;

        // You can resolve the error by using an explicit conversion.
        dc = (DerivedClass)mc;
    }  
}  
  
class DerivedClass : MyClass  
{  
}  

error CS0266: Cannot implicitly convert type ‘object’ to ‘int’. An
explicit conversion exists (are you missing a cast?)

int dd= 6000;
sqlCmdDefaultTime = new SqlCommand("myQuery", sqlCon);
sqlDefaultTime = sqlCmdDefaultTime.ExecuteReader();
while (sqlDefaultTime.Read())
{
      dd= sqlDefaultTime[1];
}

how can i cast

Amar Palsapure's user avatar

asked Jan 17, 2012 at 12:57

Br3x's user avatar

2

Simple cast to int:

dd = (int)sqlDefaultTime[1];

answered Jan 17, 2012 at 12:58

ken2k's user avatar

ken2kken2k

48k10 gold badges114 silver badges175 bronze badges

Try this…

int.TryParse(sqlDefaultTime[1].ToString(), out dd);

in the event that the parse is successful dd will now be a new value.

Unless of course the object is an int already, the you can just cast it…

dd = (int)sqlDefaultTime[1];

answered Jan 17, 2012 at 12:59

musefan's user avatar

musefanmusefan

47.8k21 gold badges134 silver badges185 bronze badges

Integer.parseInt();

a few others such as TryParse and TryParseExact provide more functionality and control.

dd= Integer.parseInt(sqlDefaultTime[1]); 

should do it, provided you can guarantee the value being returned is always an int.

answered Jan 17, 2012 at 12:59

Chris's user avatar

ChrisChris

2,47125 silver badges36 bronze badges

C# Compiler Error

CS0266 – Cannot implicitly convert type ‘type1’ to ‘type2’. An explicit conversion exists (are you missing a cast?)

Reason for the Error

You’ll get this error in your C# code when you try to convert between two types which cannot be implicitly converted. One of the simplest example of this error code is when you try to try to use the implicit conversion from double to int which is not allowed in C#.

For example, lets try to compile the below code snippet.

using System;

namespace DeveloperPubNamespace
using System;

namespace DeveloperPubNamespace
{
    class Program
    {
        public static void Main()
        {        
            double input = 3.2;
            // This will result in the C# error code CS0266
            int outPut = input;

            Console.WriteLine(outPut);
        }
    }
}

You’ll receive the error code CS0266 when you try to build the above C# program because you are assigning the double value to an int variable and expecting the C# implicit conversion to take care of the conversion.

Error CS0266 Cannot implicitly convert type ‘double’ to ‘int’. An explicit conversion exists (are you missing a cast?) DeveloperPublish C:UsersSenthilsourcereposConsoleApp3ConsoleApp3Program.cs 11 Active

C# Error CS0266 – Cannot implicitly convert type 'type1' to 'type2'

Solution

You can fix this error in your C# program by explicitly converting to the specified type. The above program can be fixed by explicitly converting the double to int.

using System;

namespace DeveloperPubNamespace
{
    class Program
    {
        public static void Main()
        {        
            double input = 3.2;
            // This will result in the C# error code CS0266
            int outPut = (int)input;

            Console.WriteLine(outPut);
        }
    }
}

EnzoLu

0 / 0 / 0

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

Сообщений: 5

1

30.04.2020, 16:48. Показов 4176. Ответов 1

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


Студворк — интернет-сервис помощи студентам

Есть код и в нём есть генерация рандомных цифр. ну и конечно же ошибка
Ошибка в 49 строке в SteamID = a.
Ошибка CS0266 Не удается неявно преобразовать тип «int» в «ulong». Существует явное преобразование (возможно, пропущено приведение типов).

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
using System;
using Network;
using RustConnection.Base;
using RustConnection.Help;
using RustConnection.NetworkPackets;
using RustConnection.Rust;
using Client = Facepunch.Network.Raknet.Client;
 
namespace RustConnection.Manager
{
    public class NetworkManager : IWorker, IClientCallback
    {
        public static NetworkManager Instance { get; private set; }
        public Facepunch.Network.Raknet.Client BaseClient { get; set; } = null;
        public bool HaveConnection { get; private set; } = false;
 
        public void Awake()
        {
            Instance = this;
            this.BaseClient = new Client
            {
                cryptography = new NetworkCryptographyClient(),
                callbackHandler = this
            };
        }
 
        public void Update(float deltaTime)
        {
            this.BaseClient.Cycle();
        }
 
        public void Connect(string addr, int port)
        {
            this.HaveConnection = true;
            this.BaseClient.Connect(addr, port);
        }
 
        public void OnNetworkMessage(Message message)
        {
            switch (message.type)
            {
                case Message.Type.RequestUserInformation:
                    Console.WriteLine("[NetworkManager]: RequestUserInformation");
                    Random rand = new Random();
                    int a = rand.Next(0, int.MaxValue);
                    new GiveUserInformation
                    {
                        GameVersion = 2220,
                        SteamID = a,
                        Username = "Instancy",
                    }.SendTo();
                    break;
                case Message.Type.Approved:
                    Console.WriteLine("[NetworkManager]: Approved");
                    new ClientReady().SendTo();
                    message.connection.decryptIncoming = true;
                    message.connection.encryptOutgoing = true;
                    message.connection.encryptionLevel = 1;
                    break;
                case Message.Type.ConsoleCommand:
                    Console.WriteLine("[NetworkManager]: ConsoleCommand: " + message.read.String());
                    break;
                case Message.Type.ConsoleMessage:
                    Console.WriteLine("[NetworkManager]: ConsoleMessage: " + message.read.String());
                    break;
                case Message.Type.DisconnectReason:
                    Console.WriteLine("[NetworkManager]: DisconnectReason: " + message.read.String());
                    break;
                case Message.Type.RPCMessage:
                    break;
                case Message.Type.Entities:
                    break;
                case Message.Type.EntityDestroy:
                    break;
                case Message.Type.ConsoleReplicatedVars:
                    Console.WriteLine("[NetworkManager]: ConsoleReplicatedVars");
                    new ConsoleCommand
                    {
                        Command = "chat.say "PIZDEC""
                    }.SendTo();
                    break;
                case Message.Type.GroupDestroy:
                    Console.WriteLine("[NetworkManager]: GroupDestroy" );
                    break;
            }
        }
 
        public void OnClientDisconnected(string reason)
        {
            this.HaveConnection = false;
            Console.WriteLine("[NetworkManager]: OnClientDisconnected => " + reason);
        }
    }
}



0



I2um1

Злой няш

2136 / 1505 / 565

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

Сообщений: 2,881

30.04.2020, 16:52

2

Лучший ответ Сообщение было отмечено EnzoLu как решение

Решение

C#
1
SteamID = (ulong)a,



1



1 Answer

Looks to me like Product.Price is defined as an int rather than a double. We can’t know that, though, because we can’t see your class Product(). The error is extremely self-explanatory — it is telling you that you are feeding a double value to an int variable somewhere. I’m not one of the smack-down types on this board, but this is a Google question more than an SO question. IF you still need help, post your Product() class and everthing that gets sent to it.

answered Aug 27, 2016 at 1:56

Shannon Holsinger's user avatar

1

  • I disagree. The question is «why do I get this error» and the answer is «because you’re feeding a double value to an int variable.» Asked, answered.

    Aug 27, 2016 at 22:56

Понравилась статья? Поделить с друзьями:
  • Ошибка компилятора cs0236
  • Ошибка компилятора cs0200
  • Ошибка компилятора cs0120
  • Ошибка компилятора cs0115
  • Ошибка компилятора cs0103