Autor Beitrag
Felix2000
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 124



BeitragVerfasst: Mo 31.10.11 16:19 
Hi Folks !

Ich habe hier eine noch recht übersichtliche Methode, bei der während der Kompilierung ein Fehler auftritt, den ich nicht ganz verstehe. Sinn der Methode ist es eine Datenbankverbdinung zu einem MySql Datenbanksystem aufzubauen und etwas vom Typ MySqlConnection zurückzugeben. Hier der Code:

ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
        //Verbindung zum MySQL Datenbanksysten herstellen
        MySqlConnection erzeugeDatenbankverbindung()
        {
            MySqlConnection connection = null;

            try
            {
                string myConnectionString = "Server = localhost; Port = 3306; Database = formulardaten; Uid = ; Pwd = ;";

                connection = new MySqlConnection(myConnectionString);
            }
            
            catch(MySqlException e)
            {
                this.Label1_Hinweisfeld.Text = e.Message;
            }

            if (connection != null
            {
                return connection;
            }
        }


Ich erhalte die Fehlermeldung: "Nicht alle Codepfade geben einen Wert zurück."
Was genau mache ich hier falsch?

Greetz
Felix
mats74
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 189
Erhaltene Danke: 26

Win 10
VS 2017/19, C++, C#
BeitragVerfasst: Mo 31.10.11 16:34 
Hallo Felix2000

Bei der If-Anweisung fehlt der Return-Wert, wenn der Fall "== null" eintritt.
ausblenden C#-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
if (connextion != null)
{
    return connection;
}
else
{
    return "irgendetwas";
}

Daher kommt der erwähnte Fehler.

_________________
Gruss
mats74
Felix2000 Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 124



BeitragVerfasst: Mo 31.10.11 16:36 
ah ok danke, ich frage mich jetzt allerdings, was genau ich da im else zweig zurückgeben könnte, wenn kein Objekt vom Typ MySqlConnection erzeugt werden konnte? Also wie ich das konkret im Code schrreiben könnte.
mats74
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starontopic star
Beiträge: 189
Erhaltene Danke: 26

Win 10
VS 2017/19, C++, C#
BeitragVerfasst: Mo 31.10.11 16:41 
Am einfachsten lässt Du die If-Anweisung weg und gibst immer den Wert "connection" zurück.
Beim Aufruf dieser Methode prüfst Du dann den Rückgabewert ensprechend auf "null".

_________________
Gruss
mats74