Home > Mobile >  Use if() from c# .dll as if() in Winforms
Use if() from c# .dll as if() in Winforms

Time:01-16

I've been trying to figure out how use my c# dll with c# windows forms app and what I want to achieve is that inside my dll I'll create a if() condition and then use it in winforms.

Basically I want to create a function in the dll that will check if file exists and then in winforms use that as condition in button click example:

if(mydll.Classname.Function == true)

my dll code

    public class Classname
{
    static void Function()
    {
        if (File.Exists("\\blabla\\something\\app.exe"))
        {

            

        }

    }
}

and then I linked the dll to the win forms and in win forms I tried this

        private void Launch_Click(object sender, EventArgs e)
    {
        if (mydll.Classname.Function == true)
        {


        }

}

when I try this it it underlines it and I can't build it.

Any ideas? Thanks

CodePudding user response:

In .NET you create a DLL by creating a Class Library Project. You can then reference this project in your application. If this Class Library Project is in the same Solution, you can add a Project Reference to your application (WinForms) pointing to this Library. If it is in another Solution, add an Assembly Reference to the DLL (usually the one residing in the bin/Release folder).

See also: How to Add References to Your Visual Studio Project.


Now, to the design of your library function. This function must return a Boolean returning the result of the file test, that can be used in an if-statement in your application. Also, it must be public.

public static class FileFunctions
{
    public static bool AppExists()
    {
        return File.Exists(@"\blabla\something\app.exe");
    }
}

Note that I have also made the class static, so that it is not possible to create an object of this class, as it makes no sense here (var ff = new FileFunctions();).

Now, in your application, you can use this function:

private void Launch_Click(object sender, EventArgs e)
{
    if (FileFunctions.AppExists())
    {

    }
}

You cannot reference the DLL directly in the code; however, If the class is in another namespace, you must reference this namespace. either directly at the call site:

if (ClassLibraryNamespace.FileFunctions.AppExists())

... or by adding a using at the top of the code file, where there is probably already a using System;:

using ClassLibraryNamespace;

Note that I did not write if (FileFunctions.AppExeExists() == true). The if-statement requires an expression yielding a Boolean, i.e., either true or false. This is what the function returns. It does not require a comparison.

  •  Tags:  
  • Related