Static public variables in C#

Asked

Viewed 415 times

4

How can I organize my code? When programming there are variables that I am leaving in the same code at the top as:

namespace myData.MySql
{
    public partial class teste
    {
        public static string M_CPF_PROCURADOR;
        public static string strM_NirfFormatado;
        private static string m_datainicio = "";
        (...)

Would it be ideal if I create a class and discriminate them and call them when necessary? If yes could inform me how to do?

  • It’s hard to answer with just this information. Add more code, give more context, indicate what you think might be wrong.

  • For example: the calculation c= a+b, if I create a routine like private void soma(). If I put the calculation within this routine, when I need the result of c in another routine, or I leave the public variable or send by value in the routine. The question is, can I use these public variables?

1 answer

4


I start by saying I’m afraid if this partial really is necessary.

Static variables are of the class and not of the instance. That is, there is only one object in them, you cannot have several. Is that what you want? It doesn’t look like it, but I could be wrong, the part you put in there can’t be inferred. If you want to have the data in each object created for this class, the variables cannot be static.

If you need the variables accessible in several methods, just declare them private, you have no reason to be public. They would only need to be public if there was a need for direct access to them outside the class. This does not seem to be the case.

It is always better to use parameters than to access internal variables. But it is not always the best to do, depends on each case. The ideal is to have low coupling, but we can’t always or should not do this (the cost may be too high).

I see no need to create another class, according to what was demonstrated in the question, but it may be ideal if the concrete case determines something else that is not in the question. Cohesion is a good thing to achieve, but it can only be determined with sufficient data.

To nomenclature of identifiers seem well out of what establishes the . NET.

If the question is improved, I improve the answer. Ideally, you have a concrete case. With an artificial code, everything can be valid.

  • I got mustache. It was super clear!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.