Error cs1503 argument 1 cannot convert from string to char

The problem is that I keep getting this error Cannot convert from OmzetApplicatie.lib.Category to string The error occurs on this line of code: categories.Add(new Category(item)); Complete c...

The problem is that I keep getting this error

Cannot convert from OmzetApplicatie.lib.Category to string

The error occurs on this line of code:

categories.Add(new Category(item));

Complete code:

List<string> categories;

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    string[] categorynames = { "Vlees", "Snacks", "Drank", "Groenten en Fruit", "Droge voeding", "Sauzen", "Diepvries" };

    foreach (string item in categorynames)
    {
        categories.Add(new Category(item));
    }

    Product[][] products = {
            new Product[] { new Product("gehakt", 6.4M, 5.30M), new Product("hamburger", 9.0M, 6.25M), new Product("kip", 9.7M, 7.13M), new Product("biefstuk", 17.9M, 13.38M), new Product("preparé", 10.3M, 7.86M) },
            new Product[] { new Product("chips", 1.8M, 1.51M), new Product("nootjes", 7.00M, 5.83M), new Product("suikerwafels", 0.9M, 0.73M), new Product("snoep", 1.9M, 1.34M) },
            new Product[] { new Product("water", 0.3M, 0.23M), new Product("cola", 2.0M, 1.55M), new Product("ice-tea", 1.8M, 1.23M), new Product("fanta", 1.8M, 1.34M), new Product("sprite", 1.8M, 1.36M) },
            new Product[] { new Product("appels", 1.2M, 1.03M), new Product("komkommer", 0.4M, 0.36M), new Product("paprika", 2.4M, 2.05M), new Product("banaan", 1.4M, 1.15M), new Product("champignons", 0.8M, 0.63M) },
            new Product[] { new Product("spaghetti", 1.3M, 1.05M), new Product("rijst", 2.2M, 2.03M), new Product("hamburgerbroodjes", 2.4M, 2.17M), new Product("brood", 1.4M, 1.03M), new Product("macaroni", 0.3M, 0.26M) },
            new Product[] { new Product("ketchup", 2.7M, 2.27M), new Product("mayonaise", 1.7M, 1.12M), new Product("pesto", 0.8M, 0.63M), new Product("tomatensaus", 0.5M, 0.38M) },
            new Product[] { new Product("ijs", 1.7M, 1.34M), new Product("frieten", 1.7M, 1.62M), new Product("kroketten", 3.2M, 3.05M), new Product("frikandel", 1.9M, 1.62M), new Product("pizza", 2.3M, 2.16M) }
    };

    for (int i = 0; i < products.Length; i++)
    {
        foreach (Product p in products[i])
        {
            categories[i].AddProduct(p);
        }
    }
}

This is my class from my class library

namespace OmzetApplicatie.lib
{
    public class Category
    {
        public string item;
        public string[] categorynames;

        public Category(string item)
        {
            this.item = item;
        }
    }
}

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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
using System;
using System.IO;
using System.Collections.Generic;
 
namespace Grapher
{ class Program
{
    static void Main(string[] args)
    {
        string[] data = File.ReadAllLines("массив.txt");
        int length = data[0].Split(';').Length, i;
        Graph graph = new Graph();
        for (i = 0; i < length; i++)
        {
            string[] str = data[i].Split(';');
            var vertices = new Dictionary<char, int>();
            for (int j = 0; j < length; j++)
                if (Convert.ToInt32(str[j]) != 0)
                    vertices.Add(Char.Parse((j + 1).ToString()), Convert.ToInt32(str[j]));
 
            graph.add_vertex(Char.Parse((i + 1).ToString()), vertices);
        }
       
        string start = Console.ReadLine(); // Номер начального пункта
            string end = Console.ReadLine(); // Номер конечного пункта
        var result = graph.all_ways(start, end, "", 0);
 
        using (var sw = new StreamWriter("результат.txt"))
        {
            foreach (var item in result)
                sw.WriteLine(item);
            sw.WriteLine("Кратчайшее расстояние равно " + graph.shortest_path(start, end));
        }
        Console.Write("Результат был сохранен в файле результат.txt");
        Console.ReadLine();
    }
}
}
 
 
    class Graph
    {
        Dictionary<char, Dictionary<char, int>> vertices = new Dictionary<char, Dictionary<char, int>>();
        public void add_vertex(char name, Dictionary<char, int> edges)
        {
            vertices[name] = edges;
        }
        public List<string> all_ways(char current, char end, string path, int weight)
        {
            List<string> pathes = new List<string>();
            if (path.IndexOf(current.ToString() + " ") != -1)
 
                return pathes;
            else
                if (path == "")
                path = current.ToString() + " = 0";
            else
            {
                int index = path.IndexOf("=");
                string temp = path.Substring(0, index);
                string sum = path.Substring(index + 1);
                weight += Convert.ToInt32(sum);
                path = temp + "-> " + current.ToString() + " = " + weight.ToString();
            }
            if (current == end)
            {
                pathes.Add(path);
                return pathes;
            }
            foreach (KeyValuePair<char, int> pair in vertices[current])
            {
                List<string> result = all_ways(pair.Key, end, path, pair.Value);
                if (result.Count != 0)
                    pathes.AddRange(result);
            }
            return pathes;
        }
        public int shortest_path(char start, char finish)
        {
            var previous = new Dictionary<char, char>();
            var distances = new Dictionary<char, int>();
            var nodes = new List<char>();
 
            List<char> path = null;
 
            foreach (var vertex in vertices)
            {
                if (vertex.Key == start)
                {
                    distances[vertex.Key] = 0;
                }
                else
                {
                    distances[vertex.Key] = int.MaxValue;
                }
 
                nodes.Add(vertex.Key);
            }
 
            while (nodes.Count != 0)
            {
                nodes.Sort((x, y) => distances[x] - distances[y]);
 
                var smallest = nodes[0];
                nodes.Remove(smallest);
 
                if (smallest == finish)
                {
                    path = new List<char>();
                    while (previous.ContainsKey(smallest))
                    {
                        path.Add(smallest);
                        smallest = previous[smallest];
                    }
 
                    break;
                }
 
                if (distances[smallest] == int.MaxValue)
                {
                    break;
                }
 
                foreach (var neighbor in vertices[smallest])
                {
                    var alt = distances[smallest] + neighbor.Value;
                    if (alt < distances[neighbor.Key])
                    {
                        distances[neighbor.Key] = alt;
                        previous[neighbor.Key] = smallest;
                    }
                }
            }
            if (path.Count > 0)
                return distances[path[0]];
            else
                return 0;
        }
    }

Ошибку как исправить?
Вот такие ошибки:

Ошибка CS1503 Аргумент 1: не удается преобразовать из «string» в «char».

Ошибка CS1503 Аргумент 1: не удается преобразовать из «string» в «char».

Ошибка CS1503 Аргумент 2: не удается преобразовать из «string» в «char».

Ошибка CS1503 Аргумент 2: не удается преобразовать из «string» в «char».

using System;
using System.IO;
using System.Collections.Generic;
 
namespace Grapher
{ class Program
{
    static void Main(string[] args)
    {
        string[] data = File.ReadAllLines("массив.txt");
        int length = data[0].Split(';').Length, i;
        Graph graph = new Graph();
        for (i = 0; i < length; i++)
        {
            string[] str = data[i].Split(';');
            var vertices = new Dictionary<char, int>();
            for (int j = 0; j < length; j++)
                if (Convert.ToInt32(str[j]) != 0)
                    vertices.Add(Char.Parse((j + 1).ToString()), Convert.ToInt32(str[j]));
 
            graph.add_vertex(Char.Parse((i + 1).ToString()), vertices);
        }
       
        string start = Console.ReadLine(); // Номер начального пункта
            string end = Console.ReadLine(); // Номер конечного пункта
        var result = graph.all_ways(start, end, "", 0);
 
        using (var sw = new StreamWriter("результат.txt"))
        {
            foreach (var item in result)
                sw.WriteLine(item);
            sw.WriteLine("Кратчайшее расстояние равно " + graph.shortest_path(start, end));
        }
        Console.Write("Результат был сохранен в файле результат.txt");
        Console.ReadLine();
    }
}
}

    class Graph
    {
        Dictionary<char, Dictionary<char, int>> vertices = new Dictionary<char, Dictionary<char, int>>();
        public void add_vertex(char name, Dictionary<char, int> edges)
        {
            vertices[name] = edges;
        }
        public List<string> all_ways(char current, char end, string path, int weight)
        {
            List<string> pathes = new List<string>();
            if (path.IndexOf(current.ToString() + " ") != -1)
 
                return pathes;
            else
                if (path == "")
                path = current.ToString() + " = 0";
            else
            {
                int index = path.IndexOf("=");
                string temp = path.Substring(0, index);
                string sum = path.Substring(index + 1);
                weight += Convert.ToInt32(sum);
                path = temp + "-> " + current.ToString() + " = " + weight.ToString();
            }
            if (current == end)
            {
                pathes.Add(path);
                return pathes;
            }
            foreach (KeyValuePair<char, int> pair in vertices[current])
            {
                List<string> result = all_ways(pair.Key, end, path, pair.Value);
                if (result.Count != 0)
                    pathes.AddRange(result);
            }
            return pathes;
        }
        public int shortest_path(char start, char finish)
        {
            var previous = new Dictionary<char, char>();
            var distances = new Dictionary<char, int>();
            var nodes = new List<char>();
 
            List<char> path = null;
 
            foreach (var vertex in vertices)
            {
                if (vertex.Key == start)
                {
                    distances[vertex.Key] = 0;
                }
                else
                {
                    distances[vertex.Key] = int.MaxValue;
                }
 
                nodes.Add(vertex.Key);
            }
 
            while (nodes.Count != 0)
            {
                nodes.Sort((x, y) => distances[x] - distances[y]);
 
                var smallest = nodes[0];
                nodes.Remove(smallest);
 
                if (smallest == finish)
                {
                    path = new List<char>();
                    while (previous.ContainsKey(smallest))
                    {
                        path.Add(smallest);
                        smallest = previous[smallest];
                    }
 
                    break;
                }
 
                if (distances[smallest] == int.MaxValue)
                {
                    break;
                }
 
                foreach (var neighbor in vertices[smallest])
                {
                    var alt = distances[smallest] + neighbor.Value;
                    if (alt < distances[neighbor.Key])
                    {
                        distances[neighbor.Key] = alt;
                        previous[neighbor.Key] = smallest;
                    }
                }
            }
            if (path.Count > 0)
                return distances[path[0]];
            else
                return 0;
        }
    }
  • Remove From My Forums
  • Question

  • HI ! I am expirienced C++ programmer , but new to C#

    1. What is the difference between string and String ? when is each one used ?

    2. I tried to use «ToCharArray» , because I need the text in simple characters array.

    private System.Windows.Forms.TextBox UserName ;

                char [] name1;

                name1 = new char [64];

                name1 = this.UserName.Text.ToCharArray();

       But when tried to print it :

               MessageBox.Show( name1.ToString ());

       it printed on the meesage box :  «System.char [] » , which is  not
    the text that is there. 

    MessageBox.Show( this.UserName.Text );         worked fine 

    3. I dont know what is wrong . ? 

    4. Is c# characters array is like C character array or not ?

    Thanks


    good morning sunshine

Answers

  • I’m not sure why you’re getting the compile error but you shouldn’t be.  Maybe the following code (tested) will help.

    For the dll file:

    #include <stdio.h>
    
    extern "C"
    {
     __declspec(dllexport) int __stdcall say_hello(char* name)
     {
     // ...do whatever here...
    	return 411;	// return something noticable
     }
    }

    For the .Net app:

    using System;
    using System.Runtime.InteropServices;
    
    namespace WindowsApplication1
    {
     static class Program
     {
      [DllImport("lib1test1.dll", CallingConvention = CallingConvention.StdCall)]
      public static extern int say_hello(string name);
      
      static void Main()
      {
       int k = say_hello("testname");
       Console.WriteLine(k);
      }
     }
    }
    

    A few notes:

    1) EntryPoint doesn’t need to be specified if your C# function declaration has the
    exact same name that’s exported from the dll.

    2) When using pinvoke, you MUST be aware of and match the calling convention used by the C dll.  In the above, I specified __stdcall in the dll because .Net defaults to WinApi (which means it uses __stdcall on Windows machines…cdecl on WindowsCE).
      If the calling convention is other than StdCall, you must specify it in your DllImport:

    [DllImport("lib1test1.dll"
    , CallingConvention = CallingConvention.Cdecl)]
    
    

    See: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.callingconvention.aspx for more info.

    The bottom line is: If you don’t match the calling conventions you risk corrupting the stack (and getting program exceptions).

    HTH,

    ShaneB

    • Edited by

      Tuesday, February 8, 2011 1:44 AM
      arg…pasting still jacked up

    • Marked as answer by
      gilit2
      Tuesday, February 8, 2011 10:00 AM

Содержание

  1. Error cs1503 argument 1 cannot convert from string to char
  2. Answered by:
  3. Question
  4. Answers

Error cs1503 argument 1 cannot convert from string to char

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

HI ! I am expirienced C++ programmer , but new to C#

1. What is the difference between string and String ? when is each one used ?

2. I tried to use «ToCharArray» , because I need the text in simple characters array.

private System.Windows.Forms.TextBox UserName ;

char [] name1;

name1 = new char [64];

name1 = this.UserName.Text.ToCharArray();

But when tried to print it :

MessageBox.Show( name1.ToString ());

it printed on the meesage box : «System.char [] » , which is not the text that is there.

MessageBox.Show( this.UserName.Text ); worked fine

3. I dont know what is wrong . ?

4. Is c# characters array is like C character array or not ?

good morning sunshine

Answers

I’m not sure why you’re getting the compile error but you shouldn’t be. Maybe the following code (tested) will help.

For the dll file:

For the .Net app:

1) EntryPoint doesn’t need to be specified if your C# function declaration has the exact same name that’s exported from the dll.

2) When using pinvoke, you MUST be aware of and match the calling convention used by the C dll. In the above, I specified __stdcall in the dll because .Net defaults to WinApi (which means it uses __stdcall on Windows machines. cdecl on WindowsCE). If the calling convention is other than StdCall, you must specify it in your DllImport:

The bottom line is: If you don’t match the calling conventions you risk corrupting the stack (and getting program exceptions).

Источник

$begingroup$

I keep getting this error:

AssetsScriptsstore.cs(15,26): error CS1503: Argument 1: cannot convert from ‘string’ to ‘char’

When I try this:

public static string[] toArray(string str) {     
        return str.Split(" , ");
}

I know other questions have answered this but they haven’t worked. :(
Why is this happening and how can I fix it?

Thank you.

asked Jun 22, 2021 at 3:30

Human Friend's user avatar

$endgroup$

$begingroup$

The method require a char not string

public static string[] toArray(string str) {     
        return str.Split(',');
}

Try use code editor recommended by Unity like Visual Studio. It show error right away and how to fix them.
enter image description here

answered Jun 22, 2021 at 6:52

VAD's user avatar

$endgroup$

1

Not the answer you’re looking for? Browse other questions tagged

.

Понравилась статья? Поделить с друзьями:
  • Error cs0034 operator is ambiguous on operands of type vector3 and vector2
  • Error cs0030 cannot convert type string to int
  • Error cs0029 unity
  • Error cs0029 cannot implicitly convert type void to string
  • Error cs0029 cannot implicitly convert type void to int