M
M
Maxim2016-10-16 21:22:31
Data Structures
Maxim, 2016-10-16 21:22:31

NullReferenceException when returning a struct from a function?

Function to create structure

private FormData CreateFormData()
        {
            int speed = 0;
            try
            {
                speed = Convert.ToInt32(cbSpeed.SelectedItem);
            } catch (Exception e) { if (ExceptionEvent != null) ExceptionEvent(e); }

//Создание структуры с передачей пареметров string, int, string.
            return new FormData(cbCOM.SelectedItem.ToString(), speed, tbSendText.Text);  //.NullReferenceException
        }

Structure
public struct FormData
        {
            public string Port;
            public int Baud;
            public string Messenge;
            public FormData(string port, int baud, string mess) { Port = port; Baud = baud; Messenge = mess; }
        }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stanislav Makarov, 2016-10-16
@Got_Oxidus

it's most likely the cbCOM.SelectedItem you're trying to call ToString() on.

R
Roman, 2016-10-16
@yarosroman

see structure constructor parameters, string is an object and can be null.

A
Anatoliy Mikhailov, 2016-10-17
@yamaoto

return new FormData(cbCOM?.SelectedItem?.ToString(), speed, tbSendText?.Text);

https://msdn.microsoft.com/en-us/library/dn986595.aspx

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question